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.7.0;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "../interfaces/IAllowanceModule.sol";
import "../interfaces/IGnosisSafe.sol";
import "../interfaces/IGuild.sol";
import "../utils/SignatureDecoder.sol";
/// @title GuildApp Contract
/// @author RaidGuild
/// @notice Guild app allows you to monetize content and receive recurring subscriptions
/// @dev uses ERC721 standard to tokenize subscriptions
contract GuildApp is ERC721Upgradeable, AccessControlUpgradeable, SignatureDecoder, IGuild {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeMathUpgradeable for uint256;
using StringsUpgradeable for uint256;
using AddressUpgradeable for address;
struct Subscription {
uint256 tokenId;
uint256 expirationTimestamp;
}
/// @dev flag the contract as initialized
bool public override initialized;
/// @dev flag to keep track if the Guild is accepting subscriptions
bool public isActive;
/// @dev CID of Guild metadata stored on i.e. IPFS
string public metadataCID;
/// @dev current active asset accepted for subscriptions
address public tokenAddress;
/// @dev current guild subcription price
uint256 public subPrice;
/// @dev subscription period in seconds (i.e. monthly)
uint256 public subscriptionPeriod;
/// @dev subscriptions list
mapping(address => Subscription) public subscriptionByOwner;
/// @dev assets used for subscription payments
mapping(address => EnumerableSetUpgradeable.AddressSet) private _approvedTokens;
/// @dev Gnosis Safe AllowanceModule
address private _allowanceModule;
/// @dev next subscriptionID
uint256 private _nextId;
modifier onlyIfActive() {
require(isActive, "GuildApp: The Guild is disabled");
_;
}
modifier onlyGuildAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "GuildApp: Sender doesn't have an Admin role");
_;
}
event InitializedGuild(address _creator,
address _tokenAddress,
uint256 _subPrice,
uint256 _subscriptionPeriod,
GuildMetadata _metadata);
event UpdatedMetadata(string _metadataURI);
event PausedGuild(bool _isPaused);
event Withdraw(address _tokenAddress, address beneficiary, uint256 _amount);
event SubscriptionPriceChanged(address _tokenAddress, uint256 _subPrice);
event NewSubscription(address _subscriber, uint256 _tokenId, uint256 _value, uint256 expiry, bytes _data);
event RenewSubscription(address _subscriber, uint256 _tokenId, uint256 _value, uint256 expiry, bytes _data);
event Unsubscribed(uint256 _tokenId);
function __GuildApp_init_unchained(address _creator,
string memory baseURI,
string memory _metadataCID,
address _tokenAddress,
uint256 _subPrice,
uint256 _subscriptionPeriod,
address allowanceModule
) internal initializer {
require(
_tokenAddress == address(0) ||
(_tokenAddress != address(0) && IERC20Upgradeable(_tokenAddress).totalSupply() > 0),
"GuildApp: Invalid token");
isActive = true;
metadataCID = _metadataCID;
tokenAddress = _tokenAddress;
_approvedTokens[address(this)].add(_tokenAddress);
subPrice = _subPrice;
subscriptionPeriod =_subscriptionPeriod;
_setBaseURI(baseURI);
_setupRole(DEFAULT_ADMIN_ROLE, _creator);
_nextId = 0;
_allowanceModule = allowanceModule;
initialized = true;
}
/// @notice Initialize a new GuildApp contract
/// @dev Initialize inherited contracts and perform base GuildApp setup
/// @param _creator GuildApp owner
/// @param _tokenAddress asset to be accepted for payments
/// @param _subPrice subscription price in WEI
/// @param _subscriptionPeriod subscription period in seconds
/// @param _metadata guild metadata CID
/// @param allowanceModule safe module address
function initialize(address _creator,
address _tokenAddress,
uint256 _subPrice,
uint256 _subscriptionPeriod,
GuildMetadata memory _metadata,
address allowanceModule
) public override initializer {
__AccessControl_init();
__ERC721_init(_metadata.name, _metadata.symbol);
__GuildApp_init_unchained(_creator,
_metadata.baseURI,
_metadata.metadataCID,
_tokenAddress,
_subPrice,
_subscriptionPeriod,
allowanceModule);
emit InitializedGuild(_creator, _tokenAddress, _subPrice, _subscriptionPeriod, _metadata);
}
/// @notice Enable/Disable your GuildApp to accept subscription/payments
/// @dev Flag contract as active or not. Only the guild owner can execute
/// @param pause boolean to flag the Guild as active
function pauseGuild(bool pause) external override onlyGuildAdmin {
require(isActive == pause, "GuildApp: Guild already in that state");
emit PausedGuild(pause);
isActive = !pause;
}
/// @notice Withdraw balance from the Guild
/// @dev Only the guild owner can execute
/// @param _tokenAddress token asset to withdraw some balance
/// @param _amount amount to be withdraw in wei
/// @param _beneficiary beneficiary to send funds. If 0x is specified, funds will be sent to the guild owner
function withdraw(
address _tokenAddress,
uint256 _amount,
address _beneficiary
) public override onlyGuildAdmin {
require(_approvedTokens[address(this)].contains(_tokenAddress), "GuildApp: Token has not been approved");
uint256 outstandingBalance = guildBalance(_tokenAddress);
require(_amount > 0 && outstandingBalance >= _amount, "GuildApp: Not enough balance to withdraw");
address beneficiary = _beneficiary != address(0) ? _beneficiary : _msgSender();
emit Withdraw(tokenAddress, beneficiary, _amount);
IERC20Upgradeable(tokenAddress).safeTransfer(beneficiary, _amount);
}
/// @notice Update Guild subscription token and price
/// @dev can be executed only by guild owner and if guild is active
/// @param _tokenAddress token to be accepted for payments
/// @param _newSubPrice new subscription price
function updateSubscriptionPrice(
address _tokenAddress,
uint256 _newSubPrice
) public override onlyGuildAdmin onlyIfActive {
tokenAddress = _tokenAddress;
_approvedTokens[address(this)].add(_tokenAddress);
subPrice = _newSubPrice;
emit SubscriptionPriceChanged(tokenAddress, subPrice);
}
/// @notice Validate signature belongs to a Safe owner
/// @dev Currently disabled
/// @param _safeAddress Gnosis Safe contract
/// @param _transferhash Tx hash used for signing
/// @param _data owner signature
function _validateSignature(
address _safeAddress,
bytes32 _transferhash,
bytes memory _data
) internal view {
// Validate signature belongs to a Safe owner
IGnosisSafe safe = IGnosisSafe(_safeAddress);
(uint8 v, bytes32 r, bytes32 s) = signatureSplit(_data, 0);
address safeOwner;
if (v > 30) {
// To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover
safeOwner = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _transferhash)), v - 4, r, s);
} else {
// Use ecrecover with the messageHash for EOA signatures
safeOwner = ecrecover(_transferhash, v, r, s);
}
require(safe.isOwner(safeOwner), "GuildApp: Signer is not a safe owner");
}
/// @notice New subscription to the Guild
/// @dev Accepts contributions from EOA and Safes w/ enabledAllowanceModule.
/// @param _subscriber Account address
/// @param _tokenURI URI of subsription metadata
/// @param _value subsription payment value send by a user
/// @param _data allowance Tx signature used by the safe AllowanceModule
function subscribe(
address _subscriber,
string memory _tokenURI,
uint256 _value,
bytes memory _data
) public payable override onlyIfActive {
address subscriber = _subscriber;
uint256 value = _value;
if (_data.length == 0) { // condition if not using a safe
require((tokenAddress != address(0) && msg.value == 0) ||
(tokenAddress == address(0) && msg.value == value),
"GuildApp: incorrect msg.value");
} else {
// require(address(subscriber).isContract() &&
// keccak256(abi.encodePacked(IGnosisSafe(subscriber).NAME())) == keccak256(abi.encodePacked("Gnosis Safe")),
// "GuildApp: Sender is not a Gnosis Safe");
require(msg.value == 0,
"GuildApp: ETH should be transferred via AllowanceModule");
}
require(value >= subPrice, "GuildApp: Insufficient value sent");
Subscription storage subs = subscriptionByOwner[subscriber];
if (subs.tokenId == 0) {
require(subscriber == _msgSender(), "GuildApp: msg.sender must be the subscriber");
_nextId = _nextId.add(1);
subs.tokenId = _nextId;
_safeMint(subscriber, subs.tokenId);
_setTokenURI(subs.tokenId, string(abi.encodePacked(_tokenURI, "#", subs.tokenId.toString())));
subs.expirationTimestamp = subscriptionPeriod.add(block.timestamp);
emit NewSubscription(subscriber, subs.tokenId, value, subs.expirationTimestamp, _data);
} else {
require(subs.expirationTimestamp < block.timestamp, "GuildApp: sill an active subscription");
// renew or extend subscription
subs.expirationTimestamp = subs.expirationTimestamp.add(block.timestamp);
emit RenewSubscription(subscriber, subs.tokenId, value, subs.expirationTimestamp, _data);
}
if (tokenAddress != address(0) && _data.length == 0) {
// Handle payment using EOA allowances
IERC20Upgradeable(tokenAddress).safeTransferFrom(subscriber, address(this), value);
return;
}
// Else Handle payment using Safe Allowance Module
require(_allowanceModule != address(0), "GuildApp: Guild does not support Safe Allowances");
IAllowanceModule safeModule = IAllowanceModule(_allowanceModule);
uint256[5] memory allowance = safeModule.getTokenAllowance(subscriber, address(this), tokenAddress);
// allowance.amout - allowance.spent
require(allowance[0] - allowance[1] >= value, "GuildApp: Not enough allowance");
safeModule.executeAllowanceTransfer(
subscriber, // MUST be a safe
tokenAddress,
payable(this), // to
uint96(value),
address(0), // payment token
0, // payment
address(this), // delegate
"" // bypass signature check as contract signatures are not supported by the module
);
}
/// @notice Unsubscribe to the Guild
/// @dev NFT token is burned
/// @param _tokenId Subscription ID
function unsubscribe(uint256 _tokenId) public override {
require(_exists(_tokenId), "GuildApp: Subscription does not exist");
address subscriber = _msgSender();
require(subscriber == ownerOf(_tokenId), "GuildApp: Caller is not the owner of the subscription");
_burn(_tokenId);
Subscription storage subs = subscriptionByOwner[subscriber];
subs.tokenId = 0;
subs.expirationTimestamp = 0;
emit Unsubscribed(_tokenId);
}
/// @notice Get the Guild balance of a specified token
/// @param _tokenAddress asset address
/// @return current guild balanceOf `_tokenAddres`
function guildBalance(address _tokenAddress) public view override returns (uint256) {
if (_approvedTokens[address(this)].contains(_tokenAddress)) {
if (tokenAddress != address(0)) {
return IERC20Upgradeable(tokenAddress).balanceOf(address(this));
}
return address(this).balance;
}
return 0;
}
/// @notice Return if `_holder` owns a subscription with ID `_tokenId`
/// @param _tokenId subsription ID
/// @param _holder user address
/// @return true if `_holder` owns the subscription
function isSubscriptionOwner(
uint256 _tokenId,
address _holder
) public view override returns (bool) {
return ownerOf(_tokenId) == _holder;
}
/// @notice Return true if `_account` has an active subscription
/// @param _account subscriber address
/// @return true if `_account` has an active subscription
function hasActiveSubscription(address _account) public view override returns (bool) {
return subscriptionByOwner[_account].expirationTimestamp > block.timestamp;
}
/// @notice Get Subscription ID from `_account`
/// @param _account subscriber address
/// @return subscription ID that belong to `_account`
function getSubscriptionIdFor(address _account) public view override returns (uint256) {
return subscriptionByOwner[_account].tokenId;
}
/// @notice Get the subscription expiration timestamp
/// @param _account subscriber address
/// @return expiration timestamp in seconds
function getSubscriptionExpiryFor(address _account) external view override returns (uint256) {
return subscriptionByOwner[_account].expirationTimestamp;
}
/// @notice Return list of approved tokens in the guild
/// @return array of assets aproved to the Guild
function approvedTokens() public view override returns (address[] memory) {
address[] memory tokens = new address[](_approvedTokens[address(this)].length());
for (uint256 i = 0; i < _approvedTokens[address(this)].length(); i++) {
tokens[i] = _approvedTokens[address(this)].at(i);
}
return tokens;
}
/// @notice Return Guild Metadata CID
/// @return metadataCID (i.e. IPFS hash)
function getMetadata() public view override returns (string memory) {
string memory base = baseURI();
if (bytes(base).length == 0) {
return metadataCID;
}
return string(abi.encodePacked(base, metadataCID));
}
/// @notice Set Guild Metadata ID
/// @dev Only the guild owner can execute
/// @param _metadataCID new metadata CID
function setMetadata(string memory _metadataCID) external override onlyGuildAdmin onlyIfActive {
metadataCID = _metadataCID;
emit UpdatedMetadata(getMetadata());
}
receive() external payable {
}
uint256[50] private __gap;
} | @notice Get the subscription expiration timestamp @param _account subscriber address @return expiration timestamp in seconds | function getSubscriptionExpiryFor(address _account) external view override returns (uint256) {
return subscriptionByOwner[_account].expirationTimestamp;
}
| 1,796,185 | [
1,
967,
326,
4915,
7686,
2858,
225,
389,
4631,
9467,
1758,
327,
7686,
2858,
316,
3974,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
7040,
3100,
14633,
1290,
12,
2867,
389,
4631,
13,
3903,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
4915,
858,
5541,
63,
67,
4631,
8009,
19519,
4921,
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
]
|
// SPDX-License-Identifier: MIT
/*
_ _____ _
| | __ \ (_)
__| | | \/ ___ _ __ ___ ___ _ ___
/ _` | | __ / _ \ '_ \ / _ \/ __| / __|
| (_| | |_\ \ __/ | | | __/\__ \ \__ \
\__,_|\____/\___|_| |_|\___||___/_|___/
_____ _ _
/ __ \ | (_)
| / \/ | __ _ _ _ __ ___
| | | |/ _` | | '_ ` _ \
| \__/\ | (_| | | | | | | |
\____/_|\__,_|_|_| |_| |_|
*/
pragma solidity =0.8.2;
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
/**
* Slightly modified version of: https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol
* Changes include:
* - remove "./interfaces/IMerkleDistributor.sol" inheritance
* - Contract name and require statement message string changes
* - add withdrawBlock and withdrawAddress state variables and withdraw() method
*/
interface dGenesisPrimeInterface {
function claimMint(uint256 projectId,
uint256 numberOfTokens,
address claimer)
external
;
}
contract dGenesisClaim is Ownable, Pausable {
struct Claim {
uint256 projectId;
bytes32 merkleRoot;
address mintContract;
// This is a packed array of booleans.
mapping(uint256 => uint256) claimedBitMap;
}
uint256 public nextClaimId = 1;
mapping(uint256 => Claim) claims;
// This event is triggered whenever a call to #claim succeeds.
event Claimed(
uint256 claimIndex,
uint256 index,
address account,
uint256 amount
);
function addClaim(
address _mintContract,
uint256 _projectId,
bytes32 _merkleRoot
) public onlyOwner returns (uint256) {
claims[nextClaimId].mintContract = _mintContract;
claims[nextClaimId].projectId = _projectId;
claims[nextClaimId].merkleRoot = _merkleRoot;
nextClaimId = nextClaimId + 1;
return nextClaimId-1;
}
function isClaimed(uint256 claimIndex, uint256 index)
public
view
returns (bool)
{
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
uint256 claimedWord = claims[claimIndex].claimedBitMap[
claimedWordIndex
];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
function _setClaimed(uint256 claimIndex, uint256 index) private {
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
claims[claimIndex].claimedBitMap[claimedWordIndex] =
claims[claimIndex].claimedBitMap[claimedWordIndex] |
(1 << claimedBitIndex);
}
/**
* No caller permissioning needed since token is transfered to account argument,
* and there is no incentive to call function for another account.
* Can only submit claim for full claimable amount, otherwise proof verification will fail.
*/
function claim(
uint256 claimIndex,
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof
) external whenNotPaused {
require(
!isClaimed(claimIndex, index),
"dGenesisVaultClaim: Drop already claimed."
);
// Verify the merkle proof.
bytes32 node = keccak256(abi.encodePacked(index, account, amount));
require(
MerkleProof.verify(
merkleProof,
claims[claimIndex].merkleRoot,
node
),
"dGenesisVaultClaim: Invalid proof."
);
// Mark it claimed and send the token.
_setClaimed(claimIndex, index);
//mint logic goes here
dGenesisPrimeInterface(claims[claimIndex].mintContract).claimMint(claims[claimIndex].projectId,
amount,
account);
emit Claimed(claimIndex, index, account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../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
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;
}
} | * Changes include: - remove "./interfaces/IMerkleDistributor.sol" inheritance - Contract name and require statement message string changes - add withdrawBlock and withdrawAddress state variables and withdraw() method/ | interface dGenesisPrimeInterface {
function claimMint(uint256 projectId,
uint256 numberOfTokens,
address claimer)
external
;
_ _____ _
pragma solidity =0.8.2;
}
| 12,174,259 | [
1,
7173,
2341,
30,
300,
1206,
25165,
15898,
19,
3445,
264,
15609,
1669,
19293,
18,
18281,
6,
16334,
300,
13456,
508,
471,
2583,
3021,
883,
533,
3478,
300,
527,
598,
9446,
1768,
471,
598,
9446,
1887,
919,
3152,
471,
598,
9446,
1435,
707,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
5831,
302,
7642,
16786,
23327,
1358,
288,
203,
565,
445,
7516,
49,
474,
12,
11890,
5034,
9882,
16,
540,
203,
3639,
2254,
5034,
7922,
5157,
16,
203,
3639,
1758,
927,
69,
4417,
13,
203,
3639,
3903,
203,
3639,
274,
203,
377,
389,
389,
7198,
8227,
389,
1377,
203,
683,
9454,
18035,
560,
273,
20,
18,
28,
18,
22,
31,
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
]
|
./full_match/80001/0xb6EC3aCfa7027Df9831661Ce392Fadd31615A75e/sources/contracts/NFTFraction.sol | returns all the token intialized | function getTokens() public view returns(TokenNFT[] memory) {
return _tokensintialized;
}
| 850,227 | [
1,
6154,
777,
326,
1147,
509,
649,
1235,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
18349,
1435,
1071,
1476,
1135,
12,
1345,
50,
4464,
8526,
3778,
13,
288,
203,
3639,
327,
389,
7860,
474,
649,
1235,
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
]
|
pragma solidity ^0.5.2;
// File: @daostack/infra/contracts/votingMachines/IntVoteInterface.sol
interface intvoteinterface31 { //inject NONSTANDARD NAMING
//When implementing this interface please do not only override function and modifier,
//but also to keep the modifiers on the overridden functions.
modifier ONLYPROPOSALOWNER70(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING
modifier VOTABLE14(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING
event NEWPROPOSAL82( //inject NONSTANDARD NAMING
bytes32 indexed _proposalId,
address indexed _organization,
uint256 _numOfChoices,
address _proposer,
bytes32 _paramsHash
);
event EXECUTEPROPOSAL67(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
uint256 _decision,
uint256 _totalReputation
);
event VOTEPROPOSAL81( //inject NONSTANDARD NAMING
bytes32 indexed _proposalId,
address indexed _organization,
address indexed _voter,
uint256 _vote,
uint256 _reputation
);
event CANCELPROPOSAL59(bytes32 indexed _proposalId, address indexed _organization ); //inject NONSTANDARD NAMING
event CANCELVOTING5(bytes32 indexed _proposalId, address indexed _organization, address indexed _voter); //inject NONSTANDARD NAMING
function PROPOSE48( //inject NONSTANDARD NAMING
uint256 _numOfChoices,
bytes32 _proposalParameters,
address _proposer,
address _organization
) external returns(bytes32);
function VOTE79( //inject NONSTANDARD NAMING
bytes32 _proposalId,
uint256 _vote,
uint256 _rep,
address _voter
)
external
returns(bool);
function CANCELVOTE62(bytes32 _proposalId) external; //inject NONSTANDARD NAMING
function GETNUMBEROFCHOICES23(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
function ISVOTABLE72(bytes32 _proposalId) external view returns(bool); //inject NONSTANDARD NAMING
function VOTESTATUS55(bytes32 _proposalId, uint256 _choice) external view returns(uint256); //inject NONSTANDARD NAMING
function ISABSTAINALLOW86() external pure returns(bool); //inject NONSTANDARD NAMING
function GETALLOWEDRANGEOFCHOICES7() external pure returns(uint256 min, uint256 max); //inject NONSTANDARD NAMING
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
interface ierc2016 { //inject NONSTANDARD NAMING
function TRANSFER74(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE55(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM94(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TOTALSUPPLY28() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF62(address who) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE21(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
event TRANSFER49(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL97(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: @daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol
interface votingmachinecallbacksinterface79 { //inject NONSTANDARD NAMING
function MINTREPUTATION65(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING
function BURNREPUTATION8(uint256 _amount, address _owner, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING
function STAKINGTOKENTRANSFER23(ierc2016 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) //inject NONSTANDARD NAMING
external
returns(bool);
function GETTOTALREPUTATIONSUPPLY93(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
function REPUTATIONOF100(address _owner, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
function BALANCEOFSTAKINGTOKEN17(ierc2016 _stakingToken, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
contract ownable56 { //inject NONSTANDARD NAMING
address private _owner;
event OWNERSHIPTRANSFERRED0(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = msg.sender;
emit OWNERSHIPTRANSFERRED0(address(0), _owner);
}
function OWNER8() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER65() { //inject NONSTANDARD NAMING
require(ISOWNER85());
_;
}
function ISOWNER85() public view returns (bool) { //inject NONSTANDARD NAMING
return msg.sender == _owner;
}
function RENOUNCEOWNERSHIP94() public ONLYOWNER65 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED0(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP25(address newOwner) public ONLYOWNER65 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP15(newOwner);
}
function _TRANSFEROWNERSHIP15(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0));
emit OWNERSHIPTRANSFERRED0(_owner, newOwner);
_owner = newOwner;
}
}
// File: @daostack/infra/contracts/Reputation.sol
contract reputation51 is ownable56 { //inject NONSTANDARD NAMING
uint8 public decimals = 18; //Number of decimals of the smallest unit
// Event indicating minting of reputation to an address.
event MINT64(address indexed _to, uint256 _amount); //inject NONSTANDARD NAMING
// Event indicating burning of reputation for an address.
event BURN4(address indexed _from, uint256 _amount); //inject NONSTANDARD NAMING
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of reputation at a specific block number
uint128 value;
}
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// Tracks the history of the `totalSupply` of the reputation
Checkpoint[] totalSupplyHistory;
constructor(
) public
{
}
function TOTALSUPPLY28() public view returns (uint256) { //inject NONSTANDARD NAMING
return TOTALSUPPLYAT94(block.number);
}
// Query balance and totalSupply in History
function BALANCEOF62(address _owner) public view returns (uint256 balance) { //inject NONSTANDARD NAMING
return BALANCEOFAT72(_owner, block.number);
}
function BALANCEOFAT72(address _owner, uint256 _blockNumber) //inject NONSTANDARD NAMING
public view returns (uint256)
{
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
return 0;
// This will return the expected balance during normal situations
} else {
return GETVALUEAT9(balances[_owner], _blockNumber);
}
}
function TOTALSUPPLYAT94(uint256 _blockNumber) public view returns(uint256) { //inject NONSTANDARD NAMING
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
return 0;
// This will return the expected totalSupply during normal situations
} else {
return GETVALUEAT9(totalSupplyHistory, _blockNumber);
}
}
function MINT38(address _user, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING
uint256 curTotalSupply = TOTALSUPPLY28();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint256 previousBalanceTo = BALANCEOF62(_user);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
UPDATEVALUEATNOW85(totalSupplyHistory, curTotalSupply + _amount);
UPDATEVALUEATNOW85(balances[_user], previousBalanceTo + _amount);
emit MINT64(_user, _amount);
return true;
}
function BURN49(address _user, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING
uint256 curTotalSupply = TOTALSUPPLY28();
uint256 amountBurned = _amount;
uint256 previousBalanceFrom = BALANCEOF62(_user);
if (previousBalanceFrom < amountBurned) {
amountBurned = previousBalanceFrom;
}
UPDATEVALUEATNOW85(totalSupplyHistory, curTotalSupply - amountBurned);
UPDATEVALUEATNOW85(balances[_user], previousBalanceFrom - amountBurned);
emit BURN4(_user, amountBurned);
return true;
}
// Internal helper functions to query and set a value in a snapshot array
function GETVALUEAT9(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) { //inject NONSTANDARD NAMING
if (checkpoints.length == 0) {
return 0;
}
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock) {
return checkpoints[checkpoints.length-1].value;
}
if (_block < checkpoints[0].fromBlock) {
return 0;
}
// Binary search of the value in the array
uint256 min = 0;
uint256 max = checkpoints.length-1;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
function UPDATEVALUEATNOW85(Checkpoint[] storage checkpoints, uint256 _value) internal { //inject NONSTANDARD NAMING
require(uint128(_value) == _value); //check value is in the 128 bits bounderies
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
}
// File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
// File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol
library safemath4 { //inject NONSTANDARD NAMING
function MUL16(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);
return c;
}
function DIV25(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function SUB37(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD40(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD29(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
// File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
contract erc2045 is ierc2016 { //inject NONSTANDARD NAMING
using safemath4 for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function TOTALSUPPLY28() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF62(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[owner];
}
function ALLOWANCE21(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowed[owner][spender];
}
function TRANSFER74(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER44(msg.sender, to, value);
return true;
}
function APPROVE55(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit APPROVAL97(msg.sender, spender, value);
return true;
}
function TRANSFERFROM94(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_allowed[from][msg.sender] = _allowed[from][msg.sender].SUB37(value);
_TRANSFER44(from, to, value);
emit APPROVAL97(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
function INCREASEALLOWANCE67(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].ADD40(addedValue);
emit APPROVAL97(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function DECREASEALLOWANCE11(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].SUB37(subtractedValue);
emit APPROVAL97(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _TRANSFER44(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(to != address(0));
_balances[from] = _balances[from].SUB37(value);
_balances[to] = _balances[to].ADD40(value);
emit TRANSFER49(from, to, value);
}
function _MINT14(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.ADD40(value);
_balances[account] = _balances[account].ADD40(value);
emit TRANSFER49(address(0), account, value);
}
function _BURN11(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.SUB37(value);
_balances[account] = _balances[account].SUB37(value);
emit TRANSFER49(account, address(0), value);
}
function _BURNFROM86(address account, uint256 value) internal { //inject NONSTANDARD NAMING
_allowed[account][msg.sender] = _allowed[account][msg.sender].SUB37(value);
_BURN11(account, value);
emit APPROVAL97(account, msg.sender, _allowed[account][msg.sender]);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol
contract erc20burnable16 is erc2045 { //inject NONSTANDARD NAMING
function BURN49(uint256 value) public { //inject NONSTANDARD NAMING
_BURN11(msg.sender, value);
}
function BURNFROM98(address from, uint256 value) public { //inject NONSTANDARD NAMING
_BURNFROM86(from, value);
}
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/controller/DAOToken.sol
contract daotoken36 is erc2045, erc20burnable16, ownable56 { //inject NONSTANDARD NAMING
string public name;
string public symbol;
// solhint-disable-next-line const-name-snakecase
uint8 public constant decimals61 = 18; //inject NONSTANDARD NAMING
uint256 public cap;
constructor(string memory _name, string memory _symbol, uint256 _cap)
public {
name = _name;
symbol = _symbol;
cap = _cap;
}
function MINT38(address _to, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING
if (cap > 0)
require(TOTALSUPPLY28().ADD40(_amount) <= cap);
_MINT14(_to, _amount);
return true;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
library address8 { //inject NONSTANDARD NAMING
function ISCONTRACT13(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/libs/SafeERC20.sol
pragma solidity ^0.5.2;
library safeerc2019 { //inject NONSTANDARD NAMING
using address8 for address;
bytes4 constant private transfer_selector2 = bytes4(keccak256(bytes("transfer(address,uint256)"))); //inject NONSTANDARD NAMING
bytes4 constant private transferfrom_selector45 = bytes4(keccak256(bytes("transferFrom(address,address,uint256)"))); //inject NONSTANDARD NAMING
bytes4 constant private approve_selector67 = bytes4(keccak256(bytes("approve(address,uint256)"))); //inject NONSTANDARD NAMING
function SAFETRANSFER100(address _erc20Addr, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING
// Must be a contract addr first!
require(_erc20Addr.ISCONTRACT13());
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(transfer_selector2, _to, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function SAFETRANSFERFROM10(address _erc20Addr, address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING
// Must be a contract addr first!
require(_erc20Addr.ISCONTRACT13());
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(transferfrom_selector45, _from, _to, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function SAFEAPPROVE78(address _erc20Addr, address _spender, uint256 _value) internal { //inject NONSTANDARD NAMING
// Must be a contract addr first!
require(_erc20Addr.ISCONTRACT13());
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero.
require((_value == 0) || (ierc2016(_erc20Addr).ALLOWANCE21(msg.sender, _spender) == 0));
(bool success, bytes memory returnValue) =
// solhint-disable-next-line avoid-low-level-calls
_erc20Addr.call(abi.encodeWithSelector(approve_selector67, _spender, _value));
// call return false when something wrong
require(success);
//check return value
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/controller/Avatar.sol
contract avatar70 is ownable56 { //inject NONSTANDARD NAMING
using safeerc2019 for address;
string public orgName;
daotoken36 public nativeToken;
reputation51 public nativeReputation;
event GENERICCALL1(address indexed _contract, bytes _params, bool _success); //inject NONSTANDARD NAMING
event SENDETHER8(uint256 _amountInWei, address indexed _to); //inject NONSTANDARD NAMING
event EXTERNALTOKENTRANSFER37(address indexed _externalToken, address indexed _to, uint256 _value); //inject NONSTANDARD NAMING
event EXTERNALTOKENTRANSFERFROM36(address indexed _externalToken, address _from, address _to, uint256 _value); //inject NONSTANDARD NAMING
event EXTERNALTOKENAPPROVAL0(address indexed _externalToken, address _spender, uint256 _value); //inject NONSTANDARD NAMING
event RECEIVEETHER12(address indexed _sender, uint256 _value); //inject NONSTANDARD NAMING
constructor(string memory _orgName, daotoken36 _nativeToken, reputation51 _nativeReputation) public {
orgName = _orgName;
nativeToken = _nativeToken;
nativeReputation = _nativeReputation;
}
function() external payable {
emit RECEIVEETHER12(msg.sender, msg.value);
}
function GENERICCALL24(address _contract, bytes memory _data) //inject NONSTANDARD NAMING
public
ONLYOWNER65
returns(bool success, bytes memory returnValue) {
// solhint-disable-next-line avoid-low-level-calls
(success, returnValue) = _contract.call(_data);
emit GENERICCALL1(_contract, _data, success);
}
function SENDETHER91(uint256 _amountInWei, address payable _to) public ONLYOWNER65 returns(bool) { //inject NONSTANDARD NAMING
_to.transfer(_amountInWei);
emit SENDETHER8(_amountInWei, _to);
return true;
}
function EXTERNALTOKENTRANSFER67(ierc2016 _externalToken, address _to, uint256 _value) //inject NONSTANDARD NAMING
public ONLYOWNER65 returns(bool)
{
address(_externalToken).SAFETRANSFER100(_to, _value);
emit EXTERNALTOKENTRANSFER37(address(_externalToken), _to, _value);
return true;
}
function EXTERNALTOKENTRANSFERFROM68( //inject NONSTANDARD NAMING
ierc2016 _externalToken,
address _from,
address _to,
uint256 _value
)
public ONLYOWNER65 returns(bool)
{
address(_externalToken).SAFETRANSFERFROM10(_from, _to, _value);
emit EXTERNALTOKENTRANSFERFROM36(address(_externalToken), _from, _to, _value);
return true;
}
function EXTERNALTOKENAPPROVAL13(ierc2016 _externalToken, address _spender, uint256 _value) //inject NONSTANDARD NAMING
public ONLYOWNER65 returns(bool)
{
address(_externalToken).SAFEAPPROVE78(_spender, _value);
emit EXTERNALTOKENAPPROVAL0(address(_externalToken), _spender, _value);
return true;
}
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/universalSchemes/UniversalSchemeInterface.sol
contract universalschemeinterface23 { //inject NONSTANDARD NAMING
function UPDATEPARAMETERS61(bytes32 _hashedParameters) public; //inject NONSTANDARD NAMING
function GETPARAMETERSFROMCONTROLLER72(avatar70 _avatar) internal view returns(bytes32); //inject NONSTANDARD NAMING
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/globalConstraints/GlobalConstraintInterface.sol
contract globalconstraintinterface55 { //inject NONSTANDARD NAMING
enum CallPhase { Pre, Post, PreAndPost }
function PRE44( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING
function POST41( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING
function WHEN71() public returns(CallPhase); //inject NONSTANDARD NAMING
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/controller/ControllerInterface.sol
interface controllerinterface59 { //inject NONSTANDARD NAMING
function MINTREPUTATION65(uint256 _amount, address _to, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function BURNREPUTATION8(uint256 _amount, address _from, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function MINTTOKENS53(uint256 _amount, address _beneficiary, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function REGISTERSCHEME80(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function UNREGISTERSCHEME15(address _scheme, address _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function UNREGISTERSELF18(address _avatar) external returns(bool); //inject NONSTANDARD NAMING
function ADDGLOBALCONSTRAINT70(address _globalConstraint, bytes32 _params, address _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function REMOVEGLOBALCONSTRAINT6 (address _globalConstraint, address _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function UPGRADECONTROLLER96(address _newController, avatar70 _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function GENERICCALL24(address _contract, bytes calldata _data, avatar70 _avatar) //inject NONSTANDARD NAMING
external
returns(bool, bytes memory);
function SENDETHER91(uint256 _amountInWei, address payable _to, avatar70 _avatar) //inject NONSTANDARD NAMING
external returns(bool);
function EXTERNALTOKENTRANSFER67(ierc2016 _externalToken, address _to, uint256 _value, avatar70 _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function EXTERNALTOKENTRANSFERFROM68( //inject NONSTANDARD NAMING
ierc2016 _externalToken,
address _from,
address _to,
uint256 _value,
avatar70 _avatar)
external
returns(bool);
function EXTERNALTOKENAPPROVAL13(ierc2016 _externalToken, address _spender, uint256 _value, avatar70 _avatar) //inject NONSTANDARD NAMING
external
returns(bool);
function GETNATIVEREPUTATION64(address _avatar) //inject NONSTANDARD NAMING
external
view
returns(address);
function ISSCHEMEREGISTERED53( address _scheme, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING
function GETSCHEMEPARAMETERS80(address _scheme, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING
function GETGLOBALCONSTRAINTPARAMETERS50(address _globalConstraint, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING
function GETSCHEMEPERMISSIONS72(address _scheme, address _avatar) external view returns(bytes4); //inject NONSTANDARD NAMING
function GLOBALCONSTRAINTSCOUNT61(address _avatar) external view returns(uint, uint); //inject NONSTANDARD NAMING
function ISGLOBALCONSTRAINTREGISTERED65(address _globalConstraint, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/universalSchemes/UniversalScheme.sol
contract universalscheme48 is ownable56, universalschemeinterface23 { //inject NONSTANDARD NAMING
bytes32 public hashedParameters; // For other parameters.
function UPDATEPARAMETERS61( //inject NONSTANDARD NAMING
bytes32 _hashedParameters
)
public
ONLYOWNER65
{
hashedParameters = _hashedParameters;
}
function GETPARAMETERSFROMCONTROLLER72(avatar70 _avatar) internal view returns(bytes32) { //inject NONSTANDARD NAMING
require(controllerinterface59(_avatar.OWNER8()).ISSCHEMEREGISTERED53(address(this), address(_avatar)),
"scheme is not registered");
return controllerinterface59(_avatar.OWNER8()).GETSCHEMEPARAMETERS80(address(this), address(_avatar));
}
}
// File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol
library ecdsa86 { //inject NONSTANDARD NAMING
function RECOVER59(bytes32 hash, bytes memory signature) internal pure returns (address) { //inject NONSTANDARD NAMING
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.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// 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);
}
}
function TOETHSIGNEDMESSAGEHASH91(bytes32 hash) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/libs/RealMath.sol
library realmath32 { //inject NONSTANDARD NAMING
uint256 constant private real_bits92 = 256; //inject NONSTANDARD NAMING
uint256 constant private real_fbits8 = 40; //inject NONSTANDARD NAMING
uint256 constant private real_one87 = uint256(1) << real_fbits8; //inject NONSTANDARD NAMING
function POW66(uint256 realBase, uint256 exponent) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 tempRealBase = realBase;
uint256 tempExponent = exponent;
// Start with the 0th power
uint256 realResult = real_one87;
while (tempExponent != 0) {
// While there are still bits set
if ((tempExponent & 0x1) == 0x1) {
// If the low bit is set, multiply in the (many-times-squared) base
realResult = MUL16(realResult, tempRealBase);
}
// Shift off the low bit
tempExponent = tempExponent >> 1;
// Do the squaring
tempRealBase = MUL16(tempRealBase, tempRealBase);
}
// Return the final result.
return uint216(realResult / real_one87);
}
function FRACTION6(uint216 numerator, uint216 denominator) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV25(uint256(numerator) * real_one87, uint256(denominator) * real_one87);
}
function MUL16(uint256 realA, uint256 realB) private pure returns (uint256) { //inject NONSTANDARD NAMING
// When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format.
// So we just have to clip off the extra REAL_FBITS fractional bits.
return uint256((uint256(realA) * uint256(realB)) >> real_fbits8);
}
function DIV25(uint256 realNumerator, uint256 realDenominator) private pure returns (uint256) { //inject NONSTANDARD NAMING
// We use the reverse of the multiplication trick: convert numerator from
// x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point.
return uint256((uint256(realNumerator) * real_one87) / uint256(realDenominator));
}
}
// File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol
// File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/ProposalExecuteInterface.sol
interface proposalexecuteinterface9 { //inject NONSTANDARD NAMING
function EXECUTEPROPOSAL85(bytes32 _proposalId, int _decision) external returns(bool); //inject NONSTANDARD NAMING
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
// File: openzeppelin-solidity/contracts/math/Math.sol
library math46 { //inject NONSTANDARD NAMING
function MAX19(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a >= b ? a : b;
}
function MIN92(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a < b ? a : b;
}
function AVERAGE32(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/GenesisProtocolLogic.sol
contract genesisprotocollogic61 is intvoteinterface31 { //inject NONSTANDARD NAMING
using safemath4 for uint;
using math46 for uint;
using realmath32 for uint216;
using realmath32 for uint256;
using address8 for address;
enum ProposalState { None, ExpiredInQueue, Executed, Queued, PreBoosted, Boosted, QuietEndingPeriod}
enum ExecutionState { None, QueueBarCrossed, QueueTimeOut, PreBoostedBarCrossed, BoostedTimeOut, BoostedBarCrossed}
//Organization's parameters
struct Parameters {
uint256 queuedVoteRequiredPercentage; // the absolute vote percentages bar.
uint256 queuedVotePeriodLimit; //the time limit for a proposal to be in an absolute voting mode.
uint256 boostedVotePeriodLimit; //the time limit for a proposal to be in boost mode.
uint256 preBoostedVotePeriodLimit; //the time limit for a proposal
//to be in an preparation state (stable) before boosted.
uint256 thresholdConst; //constant for threshold calculation .
//threshold =thresholdConst ** (numberOfBoostedProposals)
uint256 limitExponentValue;// an upper limit for numberOfBoostedProposals
//in the threshold calculation to prevent overflow
uint256 quietEndingPeriod; //quite ending period
uint256 proposingRepReward;//proposer reputation reward.
uint256 votersReputationLossRatio;//Unsuccessful pre booster
//voters lose votersReputationLossRatio% of their reputation.
uint256 minimumDaoBounty;
uint256 daoBountyConst;//The DAO downstake for each proposal is calculate according to the formula
//(daoBountyConst * averageBoostDownstakes)/100 .
uint256 activationTime;//the point in time after which proposals can be created.
//if this address is set so only this address is allowed to vote of behalf of someone else.
address voteOnBehalf;
}
struct Voter {
uint256 vote; // YES(1) ,NO(2)
uint256 reputation; // amount of voter's reputation
bool preBoosted;
}
struct Staker {
uint256 vote; // YES(1) ,NO(2)
uint256 amount; // amount of staker's stake
uint256 amount4Bounty;// amount of staker's stake used for bounty reward calculation.
}
struct Proposal {
bytes32 organizationId; // the organization unique identifier the proposal is target to.
address callbacks; // should fulfill voting callbacks interface.
ProposalState state;
uint256 winningVote; //the winning vote.
address proposer;
//the proposal boosted period limit . it is updated for the case of quiteWindow mode.
uint256 currentBoostedVotePeriodLimit;
bytes32 paramsHash;
uint256 daoBountyRemain; //use for checking sum zero bounty claims.it is set at the proposing time.
uint256 daoBounty;
uint256 totalStakes;// Total number of tokens staked which can be redeemable by stakers.
uint256 confidenceThreshold;
//The percentage from upper stakes which the caller for the expiration was given.
uint256 expirationCallBountyPercentage;
uint[3] times; //times[0] - submittedTime
//times[1] - boostedPhaseTime
//times[2] -preBoostedPhaseTime;
// vote reputation
mapping(uint256 => uint256 ) votes;
// vote reputation
mapping(uint256 => uint256 ) preBoostedVotes;
// address voter
mapping(address => Voter ) voters;
// vote stakes
mapping(uint256 => uint256 ) stakes;
// address staker
mapping(address => Staker ) stakers;
}
event STAKE61(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _staker,
uint256 _vote,
uint256 _amount
);
event REDEEM77(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event REDEEMDAOBOUNTY80(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event REDEEMREPUTATION31(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event STATECHANGE55(bytes32 indexed _proposalId, ProposalState _proposalState); //inject NONSTANDARD NAMING
event GPEXECUTEPROPOSAL49(bytes32 indexed _proposalId, ExecutionState _executionState); //inject NONSTANDARD NAMING
event EXPIRATIONCALLBOUNTY13(bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount); //inject NONSTANDARD NAMING
mapping(bytes32=>Parameters) public parameters; // A mapping from hashes to parameters
mapping(bytes32=>Proposal) public proposals; // Mapping from the ID of the proposal to the proposal itself.
mapping(bytes32=>uint) public orgBoostedProposalsCnt;
//organizationId => organization
mapping(bytes32 => address ) public organizations;
//organizationId => averageBoostDownstakes
mapping(bytes32 => uint256 ) public averagesDownstakesOfBoosted;
uint256 constant public num_of_choices20 = 2; //inject NONSTANDARD NAMING
uint256 constant public no97 = 2; //inject NONSTANDARD NAMING
uint256 constant public yes52 = 1; //inject NONSTANDARD NAMING
uint256 public proposalsCnt; // Total number of proposals
ierc2016 public stakingToken;
address constant private gen_token_address24 = 0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf; //inject NONSTANDARD NAMING
uint256 constant private max_boosted_proposals66 = 4096; //inject NONSTANDARD NAMING
constructor(ierc2016 _stakingToken) public {
//The GEN token (staking token) address is hard coded in the contract by GEN_TOKEN_ADDRESS .
//This will work for a network which already hosted the GEN token on this address (e.g mainnet).
//If such contract address does not exist in the network (e.g ganache)
//the contract will use the _stakingToken param as the
//staking token address.
if (address(gen_token_address24).ISCONTRACT13()) {
stakingToken = ierc2016(gen_token_address24);
} else {
stakingToken = _stakingToken;
}
}
modifier VOTABLE14(bytes32 _proposalId) { //inject NONSTANDARD NAMING
require(_ISVOTABLE26(_proposalId));
_;
}
function PROPOSE48(uint256, bytes32 _paramsHash, address _proposer, address _organization) //inject NONSTANDARD NAMING
external
returns(bytes32)
{
// solhint-disable-next-line not-rely-on-time
require(now > parameters[_paramsHash].activationTime, "not active yet");
//Check parameters existence.
require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50);
// Generate a unique ID:
bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt));
proposalsCnt = proposalsCnt.ADD40(1);
// Open proposal:
Proposal memory proposal;
proposal.callbacks = msg.sender;
proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization));
proposal.state = ProposalState.Queued;
// solhint-disable-next-line not-rely-on-time
proposal.times[0] = now;//submitted time
proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit;
proposal.proposer = _proposer;
proposal.winningVote = no97;
proposal.paramsHash = _paramsHash;
if (organizations[proposal.organizationId] == address(0)) {
if (_organization == address(0)) {
organizations[proposal.organizationId] = msg.sender;
} else {
organizations[proposal.organizationId] = _organization;
}
}
//calc dao bounty
uint256 daoBounty =
parameters[_paramsHash].daoBountyConst.MUL16(averagesDownstakesOfBoosted[proposal.organizationId]).DIV25(100);
if (daoBounty < parameters[_paramsHash].minimumDaoBounty) {
proposal.daoBountyRemain = parameters[_paramsHash].minimumDaoBounty;
} else {
proposal.daoBountyRemain = daoBounty;
}
proposal.totalStakes = proposal.daoBountyRemain;
proposals[proposalId] = proposal;
proposals[proposalId].stakes[no97] = proposal.daoBountyRemain;//dao downstake on the proposal
Staker storage staker = proposals[proposalId].stakers[organizations[proposal.organizationId]];
staker.vote = no97;
staker.amount = proposal.daoBountyRemain;
emit NEWPROPOSAL82(proposalId, organizations[proposal.organizationId], num_of_choices20, _proposer, _paramsHash);
return proposalId;
}
function EXECUTEBOOSTED98(bytes32 _proposalId) external returns(uint256 expirationCallBounty) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Boosted);
require(_EXECUTE0(_proposalId), "proposal need to expire");
uint256 expirationCallBountyPercentage =
// solhint-disable-next-line not-rely-on-time
(uint(1).ADD40(now.SUB37(proposal.currentBoostedVotePeriodLimit.ADD40(proposal.times[1])).DIV25(15)));
if (expirationCallBountyPercentage > 100) {
expirationCallBountyPercentage = 100;
}
proposal.expirationCallBountyPercentage = expirationCallBountyPercentage;
expirationCallBounty = expirationCallBountyPercentage.MUL16(proposal.stakes[yes52]).DIV25(100);
require(stakingToken.TRANSFER74(msg.sender, expirationCallBounty), "transfer to msg.sender failed");
emit EXPIRATIONCALLBOUNTY13(_proposalId, msg.sender, expirationCallBounty);
}
function SETPARAMETERS19( //inject NONSTANDARD NAMING
uint[11] calldata _params, //use array here due to stack too deep issue.
address _voteOnBehalf
)
external
returns(bytes32)
{
require(_params[0] <= 100 && _params[0] >= 50, "50 <= queuedVoteRequiredPercentage <= 100");
require(_params[4] <= 16000 && _params[4] > 1000, "1000 < thresholdConst <= 16000");
require(_params[7] <= 100, "votersReputationLossRatio <= 100");
require(_params[2] >= _params[5], "boostedVotePeriodLimit >= quietEndingPeriod");
require(_params[8] > 0, "minimumDaoBounty should be > 0");
require(_params[9] > 0, "daoBountyConst should be > 0");
bytes32 paramsHash = GETPARAMETERSHASH35(_params, _voteOnBehalf);
//set a limit for power for a given alpha to prevent overflow
uint256 limitExponent = 172;//for alpha less or equal 2
uint256 j = 2;
for (uint256 i = 2000; i < 16000; i = i*2) {
if ((_params[4] > i) && (_params[4] <= i*2)) {
limitExponent = limitExponent/j;
break;
}
j++;
}
parameters[paramsHash] = Parameters({
queuedVoteRequiredPercentage: _params[0],
queuedVotePeriodLimit: _params[1],
boostedVotePeriodLimit: _params[2],
preBoostedVotePeriodLimit: _params[3],
thresholdConst:uint216(_params[4]).FRACTION6(uint216(1000)),
limitExponentValue:limitExponent,
quietEndingPeriod: _params[5],
proposingRepReward: _params[6],
votersReputationLossRatio:_params[7],
minimumDaoBounty:_params[8],
daoBountyConst:_params[9],
activationTime:_params[10],
voteOnBehalf:_voteOnBehalf
});
return paramsHash;
}
// solhint-disable-next-line function-max-lines,code-complexity
function REDEEM91(bytes32 _proposalId, address _beneficiary) public returns (uint[3] memory rewards) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
require((proposal.state == ProposalState.Executed)||(proposal.state == ProposalState.ExpiredInQueue),
"Proposal should be Executed or ExpiredInQueue");
Parameters memory params = parameters[proposal.paramsHash];
uint256 lostReputation;
if (proposal.winningVote == yes52) {
lostReputation = proposal.preBoostedVotes[no97];
} else {
lostReputation = proposal.preBoostedVotes[yes52];
}
lostReputation = (lostReputation.MUL16(params.votersReputationLossRatio))/100;
//as staker
Staker storage staker = proposal.stakers[_beneficiary];
if (staker.amount > 0) {
if (proposal.state == ProposalState.ExpiredInQueue) {
//Stakes of a proposal that expires in Queue are sent back to stakers
rewards[0] = staker.amount;
} else if (staker.vote == proposal.winningVote) {
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
uint256 totalStakes = proposal.stakes[yes52].ADD40(proposal.stakes[no97]);
if (staker.vote == yes52) {
uint256 _totalStakes =
((totalStakes.MUL16(100 - proposal.expirationCallBountyPercentage))/100) - proposal.daoBounty;
rewards[0] = (staker.amount.MUL16(_totalStakes))/totalWinningStakes;
} else {
rewards[0] = (staker.amount.MUL16(totalStakes))/totalWinningStakes;
if (organizations[proposal.organizationId] == _beneficiary) {
//dao redeem it reward
rewards[0] = rewards[0].SUB37(proposal.daoBounty);
}
}
}
staker.amount = 0;
}
//as voter
Voter storage voter = proposal.voters[_beneficiary];
if ((voter.reputation != 0) && (voter.preBoosted)) {
if (proposal.state == ProposalState.ExpiredInQueue) {
//give back reputation for the voter
rewards[1] = ((voter.reputation.MUL16(params.votersReputationLossRatio))/100);
} else if (proposal.winningVote == voter.vote) {
uint256 preBoostedVotes = proposal.preBoostedVotes[yes52].ADD40(proposal.preBoostedVotes[no97]);
rewards[1] = ((voter.reputation.MUL16(params.votersReputationLossRatio))/100)
.ADD40((voter.reputation.MUL16(lostReputation))/preBoostedVotes);
}
voter.reputation = 0;
}
//as proposer
if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == yes52)&&(proposal.proposer != address(0))) {
rewards[2] = params.proposingRepReward;
proposal.proposer = address(0);
}
if (rewards[0] != 0) {
proposal.totalStakes = proposal.totalStakes.SUB37(rewards[0]);
require(stakingToken.TRANSFER74(_beneficiary, rewards[0]), "transfer to beneficiary failed");
emit REDEEM77(_proposalId, organizations[proposal.organizationId], _beneficiary, rewards[0]);
}
if (rewards[1].ADD40(rewards[2]) != 0) {
votingmachinecallbacksinterface79(proposal.callbacks)
.MINTREPUTATION65(rewards[1].ADD40(rewards[2]), _beneficiary, _proposalId);
emit REDEEMREPUTATION31(
_proposalId,
organizations[proposal.organizationId],
_beneficiary,
rewards[1].ADD40(rewards[2])
);
}
}
function REDEEMDAOBOUNTY7(bytes32 _proposalId, address _beneficiary) //inject NONSTANDARD NAMING
public
returns(uint256 redeemedAmount, uint256 potentialAmount) {
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Executed);
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
Staker storage staker = proposal.stakers[_beneficiary];
if (
(staker.amount4Bounty > 0)&&
(staker.vote == proposal.winningVote)&&
(proposal.winningVote == yes52)&&
(totalWinningStakes != 0)) {
//as staker
potentialAmount = (staker.amount4Bounty * proposal.daoBounty)/totalWinningStakes;
}
if ((potentialAmount != 0)&&
(votingmachinecallbacksinterface79(proposal.callbacks)
.BALANCEOFSTAKINGTOKEN17(stakingToken, _proposalId) >= potentialAmount)) {
staker.amount4Bounty = 0;
proposal.daoBountyRemain = proposal.daoBountyRemain.SUB37(potentialAmount);
require(
votingmachinecallbacksinterface79(proposal.callbacks)
.STAKINGTOKENTRANSFER23(stakingToken, _beneficiary, potentialAmount, _proposalId));
redeemedAmount = potentialAmount;
emit REDEEMDAOBOUNTY80(_proposalId, organizations[proposal.organizationId], _beneficiary, redeemedAmount);
}
}
function SHOULDBOOST32(bytes32 _proposalId) public view returns(bool) { //inject NONSTANDARD NAMING
Proposal memory proposal = proposals[_proposalId];
return (_SCORE65(_proposalId) > THRESHOLD35(proposal.paramsHash, proposal.organizationId));
}
function THRESHOLD35(bytes32 _paramsHash, bytes32 _organizationId) public view returns(uint256) { //inject NONSTANDARD NAMING
uint256 power = orgBoostedProposalsCnt[_organizationId];
Parameters storage params = parameters[_paramsHash];
if (power > params.limitExponentValue) {
power = params.limitExponentValue;
}
return params.thresholdConst.POW66(power);
}
function GETPARAMETERSHASH35( //inject NONSTANDARD NAMING
uint[11] memory _params,//use array here due to stack too deep issue.
address _voteOnBehalf
)
public
pure
returns(bytes32)
{
//double call to keccak256 to avoid deep stack issue when call with too many params.
return keccak256(
abi.encodePacked(
keccak256(
abi.encodePacked(
_params[0],
_params[1],
_params[2],
_params[3],
_params[4],
_params[5],
_params[6],
_params[7],
_params[8],
_params[9],
_params[10])
),
_voteOnBehalf
));
}
// solhint-disable-next-line function-max-lines,code-complexity
function _EXECUTE0(bytes32 _proposalId) internal VOTABLE14(_proposalId) returns(bool) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
Proposal memory tmpProposal = proposal;
uint256 totalReputation =
votingmachinecallbacksinterface79(proposal.callbacks).GETTOTALREPUTATIONSUPPLY93(_proposalId);
//first divide by 100 to prevent overflow
uint256 executionBar = (totalReputation/100) * params.queuedVoteRequiredPercentage;
ExecutionState executionState = ExecutionState.None;
uint256 averageDownstakesOfBoosted;
uint256 confidenceThreshold;
if (proposal.votes[proposal.winningVote] > executionBar) {
// someone crossed the absolute vote execution bar.
if (proposal.state == ProposalState.Queued) {
executionState = ExecutionState.QueueBarCrossed;
} else if (proposal.state == ProposalState.PreBoosted) {
executionState = ExecutionState.PreBoostedBarCrossed;
} else {
executionState = ExecutionState.BoostedBarCrossed;
}
proposal.state = ProposalState.Executed;
} else {
if (proposal.state == ProposalState.Queued) {
// solhint-disable-next-line not-rely-on-time
if ((now - proposal.times[0]) >= params.queuedVotePeriodLimit) {
proposal.state = ProposalState.ExpiredInQueue;
proposal.winningVote = no97;
executionState = ExecutionState.QueueTimeOut;
} else {
confidenceThreshold = THRESHOLD35(proposal.paramsHash, proposal.organizationId);
if (_SCORE65(_proposalId) > confidenceThreshold) {
//change proposal mode to PreBoosted mode.
proposal.state = ProposalState.PreBoosted;
// solhint-disable-next-line not-rely-on-time
proposal.times[2] = now;
proposal.confidenceThreshold = confidenceThreshold;
}
}
}
if (proposal.state == ProposalState.PreBoosted) {
confidenceThreshold = THRESHOLD35(proposal.paramsHash, proposal.organizationId);
// solhint-disable-next-line not-rely-on-time
if ((now - proposal.times[2]) >= params.preBoostedVotePeriodLimit) {
if ((_SCORE65(_proposalId) > confidenceThreshold) &&
(orgBoostedProposalsCnt[proposal.organizationId] < max_boosted_proposals66)) {
//change proposal mode to Boosted mode.
proposal.state = ProposalState.Boosted;
// solhint-disable-next-line not-rely-on-time
proposal.times[1] = now;
orgBoostedProposalsCnt[proposal.organizationId]++;
//add a value to average -> average = average + ((value - average) / nbValues)
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
// solium-disable-next-line indentation
averagesDownstakesOfBoosted[proposal.organizationId] =
uint256(int256(averageDownstakesOfBoosted) +
((int256(proposal.stakes[no97])-int256(averageDownstakesOfBoosted))/
int256(orgBoostedProposalsCnt[proposal.organizationId])));
}
} else { //check the Confidence level is stable
uint256 proposalScore = _SCORE65(_proposalId);
if (proposalScore <= proposal.confidenceThreshold.MIN92(confidenceThreshold)) {
proposal.state = ProposalState.Queued;
} else if (proposal.confidenceThreshold > proposalScore) {
proposal.confidenceThreshold = confidenceThreshold;
}
}
}
}
if ((proposal.state == ProposalState.Boosted) ||
(proposal.state == ProposalState.QuietEndingPeriod)) {
// solhint-disable-next-line not-rely-on-time
if ((now - proposal.times[1]) >= proposal.currentBoostedVotePeriodLimit) {
proposal.state = ProposalState.Executed;
executionState = ExecutionState.BoostedTimeOut;
}
}
if (executionState != ExecutionState.None) {
if ((executionState == ExecutionState.BoostedTimeOut) ||
(executionState == ExecutionState.BoostedBarCrossed)) {
orgBoostedProposalsCnt[tmpProposal.organizationId] =
orgBoostedProposalsCnt[tmpProposal.organizationId].SUB37(1);
//remove a value from average = ((average * nbValues) - value) / (nbValues - 1);
uint256 boostedProposals = orgBoostedProposalsCnt[tmpProposal.organizationId];
if (boostedProposals == 0) {
averagesDownstakesOfBoosted[proposal.organizationId] = 0;
} else {
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
averagesDownstakesOfBoosted[proposal.organizationId] =
(averageDownstakesOfBoosted.MUL16(boostedProposals+1).SUB37(proposal.stakes[no97]))/boostedProposals;
}
}
emit EXECUTEPROPOSAL67(
_proposalId,
organizations[proposal.organizationId],
proposal.winningVote,
totalReputation
);
emit GPEXECUTEPROPOSAL49(_proposalId, executionState);
proposalexecuteinterface9(proposal.callbacks).EXECUTEPROPOSAL85(_proposalId, int(proposal.winningVote));
proposal.daoBounty = proposal.daoBountyRemain;
}
if (tmpProposal.state != proposal.state) {
emit STATECHANGE55(_proposalId, proposal.state);
}
return (executionState != ExecutionState.None);
}
function _STAKE17(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _staker) internal returns(bool) { //inject NONSTANDARD NAMING
// 0 is not a valid vote.
require(_vote <= num_of_choices20 && _vote > 0, "wrong vote value");
require(_amount > 0, "staking amount should be >0");
if (_EXECUTE0(_proposalId)) {
return true;
}
Proposal storage proposal = proposals[_proposalId];
if ((proposal.state != ProposalState.PreBoosted) &&
(proposal.state != ProposalState.Queued)) {
return false;
}
// enable to increase stake only on the previous stake vote
Staker storage staker = proposal.stakers[_staker];
if ((staker.amount > 0) && (staker.vote != _vote)) {
return false;
}
uint256 amount = _amount;
require(stakingToken.TRANSFERFROM94(_staker, address(this), amount), "fail transfer from staker");
proposal.totalStakes = proposal.totalStakes.ADD40(amount); //update totalRedeemableStakes
staker.amount = staker.amount.ADD40(amount);
//This is to prevent average downstakes calculation overflow
//Note that any how GEN cap is 100000000 ether.
require(staker.amount <= 0x100000000000000000000000000000000, "staking amount is too high");
require(proposal.totalStakes <= 0x100000000000000000000000000000000, "total stakes is too high");
if (_vote == yes52) {
staker.amount4Bounty = staker.amount4Bounty.ADD40(amount);
}
staker.vote = _vote;
proposal.stakes[_vote] = amount.ADD40(proposal.stakes[_vote]);
emit STAKE61(_proposalId, organizations[proposal.organizationId], _staker, _vote, _amount);
return _EXECUTE0(_proposalId);
}
// solhint-disable-next-line function-max-lines,code-complexity
function INTERNALVOTE44(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) { //inject NONSTANDARD NAMING
require(_vote <= num_of_choices20 && _vote > 0, "0 < _vote <= 2");
if (_EXECUTE0(_proposalId)) {
return true;
}
Parameters memory params = parameters[proposals[_proposalId].paramsHash];
Proposal storage proposal = proposals[_proposalId];
// Check voter has enough reputation:
uint256 reputation = votingmachinecallbacksinterface79(proposal.callbacks).REPUTATIONOF100(_voter, _proposalId);
require(reputation > 0, "_voter must have reputation");
require(reputation >= _rep, "reputation >= _rep");
uint256 rep = _rep;
if (rep == 0) {
rep = reputation;
}
// If this voter has already voted, return false.
if (proposal.voters[_voter].reputation != 0) {
return false;
}
// The voting itself:
proposal.votes[_vote] = rep.ADD40(proposal.votes[_vote]);
//check if the current winningVote changed or there is a tie.
//for the case there is a tie the current winningVote set to NO.
if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) ||
((proposal.votes[no97] == proposal.votes[proposal.winningVote]) &&
proposal.winningVote == yes52)) {
if (proposal.state == ProposalState.Boosted &&
// solhint-disable-next-line not-rely-on-time
((now - proposal.times[1]) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod))||
proposal.state == ProposalState.QuietEndingPeriod) {
//quietEndingPeriod
if (proposal.state != ProposalState.QuietEndingPeriod) {
proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod;
proposal.state = ProposalState.QuietEndingPeriod;
}
// solhint-disable-next-line not-rely-on-time
proposal.times[1] = now;
}
proposal.winningVote = _vote;
}
proposal.voters[_voter] = Voter({
reputation: rep,
vote: _vote,
preBoosted:((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued))
});
if ((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) {
proposal.preBoostedVotes[_vote] = rep.ADD40(proposal.preBoostedVotes[_vote]);
uint256 reputationDeposit = (params.votersReputationLossRatio.MUL16(rep))/100;
votingmachinecallbacksinterface79(proposal.callbacks).BURNREPUTATION8(reputationDeposit, _voter, _proposalId);
}
emit VOTEPROPOSAL81(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep);
return _EXECUTE0(_proposalId);
}
function _SCORE65(bytes32 _proposalId) internal view returns(uint256) { //inject NONSTANDARD NAMING
Proposal storage proposal = proposals[_proposalId];
//proposal.stakes[NO] cannot be zero as the dao downstake > 0 for each proposal.
return proposal.stakes[yes52]/proposal.stakes[no97];
}
function _ISVOTABLE26(bytes32 _proposalId) internal view returns(bool) { //inject NONSTANDARD NAMING
ProposalState pState = proposals[_proposalId].state;
return ((pState == ProposalState.PreBoosted)||
(pState == ProposalState.Boosted)||
(pState == ProposalState.QuietEndingPeriod)||
(pState == ProposalState.Queued)
);
}
}
// File: @daostack/infra/contracts/votingMachines/GenesisProtocol.sol
contract genesisprotocol36 is intvoteinterface31, genesisprotocollogic61 { //inject NONSTANDARD NAMING
using ecdsa86 for bytes32;
// Digest describing the data the user signs according EIP 712.
// Needs to match what is passed to Metamask.
bytes32 public constant delegation_hash_eip71264 = //inject NONSTANDARD NAMING
keccak256(abi.encodePacked(
"address GenesisProtocolAddress",
"bytes32 ProposalId",
"uint256 Vote",
"uint256 AmountToStake",
"uint256 Nonce"
));
mapping(address=>uint256) public stakesNonce; //stakes Nonce
constructor(ierc2016 _stakingToken)
public
// solhint-disable-next-line no-empty-blocks
genesisprotocollogic61(_stakingToken) {
}
function STAKE3(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) { //inject NONSTANDARD NAMING
return _STAKE17(_proposalId, _vote, _amount, msg.sender);
}
function STAKEWITHSIGNATURE10( //inject NONSTANDARD NAMING
bytes32 _proposalId,
uint256 _vote,
uint256 _amount,
uint256 _nonce,
uint256 _signatureType,
bytes calldata _signature
)
external
returns(bool)
{
// Recreate the digest the user signed
bytes32 delegationDigest;
if (_signatureType == 2) {
delegationDigest = keccak256(
abi.encodePacked(
delegation_hash_eip71264, keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
)
)
);
} else {
delegationDigest = keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
).TOETHSIGNEDMESSAGEHASH91();
}
address staker = delegationDigest.RECOVER59(_signature);
//a garbage staker address due to wrong signature will revert due to lack of approval and funds.
require(staker != address(0), "staker address cannot be 0");
require(stakesNonce[staker] == _nonce);
stakesNonce[staker] = stakesNonce[staker].ADD40(1);
return _STAKE17(_proposalId, _vote, _amount, staker);
}
function VOTE79(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter) //inject NONSTANDARD NAMING
external
VOTABLE14(_proposalId)
returns(bool) {
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
address voter;
if (params.voteOnBehalf != address(0)) {
require(msg.sender == params.voteOnBehalf);
voter = _voter;
} else {
voter = msg.sender;
}
return INTERNALVOTE44(_proposalId, voter, _vote, _amount);
}
function CANCELVOTE62(bytes32 _proposalId) external VOTABLE14(_proposalId) { //inject NONSTANDARD NAMING
//this is not allowed
return;
}
function EXECUTE34(bytes32 _proposalId) external VOTABLE14(_proposalId) returns(bool) { //inject NONSTANDARD NAMING
return _EXECUTE0(_proposalId);
}
function GETNUMBEROFCHOICES23(bytes32) external view returns(uint256) { //inject NONSTANDARD NAMING
return num_of_choices20;
}
function GETPROPOSALTIMES43(bytes32 _proposalId) external view returns(uint[3] memory times) { //inject NONSTANDARD NAMING
return proposals[_proposalId].times;
}
function VOTEINFO83(bytes32 _proposalId, address _voter) external view returns(uint, uint) { //inject NONSTANDARD NAMING
Voter memory voter = proposals[_proposalId].voters[_voter];
return (voter.vote, voter.reputation);
}
function VOTESTATUS55(bytes32 _proposalId, uint256 _choice) external view returns(uint256) { //inject NONSTANDARD NAMING
return proposals[_proposalId].votes[_choice];
}
function ISVOTABLE72(bytes32 _proposalId) external view returns(bool) { //inject NONSTANDARD NAMING
return _ISVOTABLE26(_proposalId);
}
function PROPOSALSTATUS51(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) { //inject NONSTANDARD NAMING
return (
proposals[_proposalId].preBoostedVotes[yes52],
proposals[_proposalId].preBoostedVotes[no97],
proposals[_proposalId].stakes[yes52],
proposals[_proposalId].stakes[no97]
);
}
function GETPROPOSALORGANIZATION83(bytes32 _proposalId) external view returns(bytes32) { //inject NONSTANDARD NAMING
return (proposals[_proposalId].organizationId);
}
function GETSTAKER73(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) { //inject NONSTANDARD NAMING
return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount);
}
function VOTESTAKE72(bytes32 _proposalId, uint256 _vote) external view returns(uint256) { //inject NONSTANDARD NAMING
return proposals[_proposalId].stakes[_vote];
}
function WINNINGVOTE73(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
return proposals[_proposalId].winningVote;
}
function STATE40(bytes32 _proposalId) external view returns(ProposalState) { //inject NONSTANDARD NAMING
return proposals[_proposalId].state;
}
function ISABSTAINALLOW86() external pure returns(bool) { //inject NONSTANDARD NAMING
return false;
}
function GETALLOWEDRANGEOFCHOICES7() external pure returns(uint256 min, uint256 max) { //inject NONSTANDARD NAMING
return (yes52, no97);
}
function SCORE19(bytes32 _proposalId) public view returns(uint256) { //inject NONSTANDARD NAMING
return _SCORE65(_proposalId);
}
}
// File: /Users/oren/daostack/daostack2/daostack/contracts/votingMachines/VotingMachineCallbacks.sol
contract votingmachinecallbacks93 is votingmachinecallbacksinterface79 { //inject NONSTANDARD NAMING
struct ProposalInfo {
uint256 blockNumber; // the proposal's block number
avatar70 avatar; // the proposal's avatar
address votingMachine;
}
modifier ONLYVOTINGMACHINE57(bytes32 _proposalId) { //inject NONSTANDARD NAMING
require(msg.sender == proposalsInfo[_proposalId].votingMachine, "only VotingMachine");
_;
}
//proposalId -> ProposalInfo
mapping(bytes32 => ProposalInfo ) public proposalsInfo;
function MINTREPUTATION65(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING
external
ONLYVOTINGMACHINE57(_proposalId)
returns(bool)
{
avatar70 avatar = proposalsInfo[_proposalId].avatar;
if (avatar == avatar70(0)) {
return false;
}
return controllerinterface59(avatar.OWNER8()).MINTREPUTATION65(_amount, _beneficiary, address(avatar));
}
function BURNREPUTATION8(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING
external
ONLYVOTINGMACHINE57(_proposalId)
returns(bool)
{
avatar70 avatar = proposalsInfo[_proposalId].avatar;
if (avatar == avatar70(0)) {
return false;
}
return controllerinterface59(avatar.OWNER8()).BURNREPUTATION8(_amount, _beneficiary, address(avatar));
}
function STAKINGTOKENTRANSFER23( //inject NONSTANDARD NAMING
ierc2016 _stakingToken,
address _beneficiary,
uint256 _amount,
bytes32 _proposalId)
external
ONLYVOTINGMACHINE57(_proposalId)
returns(bool)
{
avatar70 avatar = proposalsInfo[_proposalId].avatar;
if (avatar == avatar70(0)) {
return false;
}
return controllerinterface59(avatar.OWNER8()).EXTERNALTOKENTRANSFER67(_stakingToken, _beneficiary, _amount, avatar);
}
function BALANCEOFSTAKINGTOKEN17(ierc2016 _stakingToken, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
avatar70 avatar = proposalsInfo[_proposalId].avatar;
if (proposalsInfo[_proposalId].avatar == avatar70(0)) {
return 0;
}
return _stakingToken.BALANCEOF62(address(avatar));
}
function GETTOTALREPUTATIONSUPPLY93(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
ProposalInfo memory proposal = proposalsInfo[_proposalId];
if (proposal.avatar == avatar70(0)) {
return 0;
}
return proposal.avatar.nativeReputation().TOTALSUPPLYAT94(proposal.blockNumber);
}
function REPUTATIONOF100(address _owner, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING
ProposalInfo memory proposal = proposalsInfo[_proposalId];
if (proposal.avatar == avatar70(0)) {
return 0;
}
return proposal.avatar.nativeReputation().BALANCEOFAT72(_owner, proposal.blockNumber);
}
}
// File: contracts/universalSchemes/GenericScheme.sol
contract genericscheme3 is universalscheme48, votingmachinecallbacks93, proposalexecuteinterface9 { //inject NONSTANDARD NAMING
event NEWCALLPROPOSAL18( //inject NONSTANDARD NAMING
address indexed _avatar,
bytes32 indexed _proposalId,
bytes _callData,
string _descriptionHash
);
event PROPOSALEXECUTED2( //inject NONSTANDARD NAMING
address indexed _avatar,
bytes32 indexed _proposalId,
bytes _genericCallReturnValue
);
event PROPOSALEXECUTEDBYVOTINGMACHINE53( //inject NONSTANDARD NAMING
address indexed _avatar,
bytes32 indexed _proposalId,
int256 _param
);
event PROPOSALDELETED34(address indexed _avatar, bytes32 indexed _proposalId); //inject NONSTANDARD NAMING
// Details of a voting proposal:
struct CallProposal {
bytes callData;
bool exist;
bool passed;
}
// A mapping from the organization (Avatar) address to the saved data of the organization:
mapping(address=>mapping(bytes32=>CallProposal)) public organizationsProposals;
struct Parameters {
intvoteinterface31 intVote;
bytes32 voteParams;
address contractToCall;
}
// A mapping from hashes to parameters (use to store a particular configuration on the controller)
mapping(bytes32=>Parameters) public parameters;
function EXECUTEPROPOSAL85(bytes32 _proposalId, int256 _decision) //inject NONSTANDARD NAMING
external
ONLYVOTINGMACHINE57(_proposalId)
returns(bool) {
avatar70 avatar = proposalsInfo[_proposalId].avatar;
CallProposal storage proposal = organizationsProposals[address(avatar)][_proposalId];
require(proposal.exist, "must be a live proposal");
require(proposal.passed == false, "cannot execute twice");
if (_decision == 1) {
proposal.passed = true;
EXECUTE34(_proposalId);
} else {
delete organizationsProposals[address(avatar)][_proposalId];
emit PROPOSALDELETED34(address(avatar), _proposalId);
}
emit PROPOSALEXECUTEDBYVOTINGMACHINE53(address(avatar), _proposalId, _decision);
return true;
}
function EXECUTE34(bytes32 _proposalId) public { //inject NONSTANDARD NAMING
avatar70 avatar = proposalsInfo[_proposalId].avatar;
Parameters memory params = parameters[GETPARAMETERSFROMCONTROLLER72(avatar)];
CallProposal storage proposal = organizationsProposals[address(avatar)][_proposalId];
require(proposal.exist, "must be a live proposal");
require(proposal.passed, "proposal must passed by voting machine");
proposal.exist = false;
bytes memory genericCallReturnValue;
bool success;
controllerinterface59 controller = controllerinterface59(avatar70(avatar).OWNER8());
(success, genericCallReturnValue) = controller.GENERICCALL24(params.contractToCall, proposal.callData, avatar);
if (success) {
delete organizationsProposals[address(avatar)][_proposalId];
emit PROPOSALDELETED34(address(avatar), _proposalId);
emit PROPOSALEXECUTED2(address(avatar), _proposalId, genericCallReturnValue);
} else {
proposal.exist = true;
}
}
function SETPARAMETERS19( //inject NONSTANDARD NAMING
bytes32 _voteParams,
intvoteinterface31 _intVote,
address _contractToCall
) public returns(bytes32)
{
bytes32 paramsHash = GETPARAMETERSHASH35(_voteParams, _intVote, _contractToCall);
parameters[paramsHash].voteParams = _voteParams;
parameters[paramsHash].intVote = _intVote;
parameters[paramsHash].contractToCall = _contractToCall;
return paramsHash;
}
function GETPARAMETERSHASH35( //inject NONSTANDARD NAMING
bytes32 _voteParams,
intvoteinterface31 _intVote,
address _contractToCall
) public pure returns(bytes32)
{
return keccak256(abi.encodePacked(_voteParams, _intVote, _contractToCall));
}
function PROPOSECALL64(avatar70 _avatar, bytes memory _callData, string memory _descriptionHash) //inject NONSTANDARD NAMING
public
returns(bytes32)
{
Parameters memory params = parameters[GETPARAMETERSFROMCONTROLLER72(_avatar)];
intvoteinterface31 intVote = params.intVote;
bytes32 proposalId = intVote.PROPOSE48(2, params.voteParams, msg.sender, address(_avatar));
organizationsProposals[address(_avatar)][proposalId] = CallProposal({
callData: _callData,
exist: true,
passed: false
});
proposalsInfo[proposalId] = ProposalInfo({
blockNumber:block.number,
avatar:_avatar,
votingMachine:address(params.intVote)
});
emit NEWCALLPROPOSAL18(address(_avatar), proposalId, _callData, _descriptionHash);
return proposalId;
}
function GETCONTRACTTOCALL27(avatar70 _avatar) public view returns(address) { //inject NONSTANDARD NAMING
return parameters[GETPARAMETERSFROMCONTROLLER72(_avatar)].contractToCall;
}
} | inject NONSTANDARD NAMING
| function MINTREPUTATION65(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool); | 12,775,660 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
490,
3217,
862,
4762,
2689,
9222,
12,
11890,
5034,
389,
8949,
16,
1758,
389,
70,
4009,
74,
14463,
814,
16,
1731,
1578,
389,
685,
8016,
548,
13,
3903,
1135,
12,
6430,
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
]
|
pragma solidity ^0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @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) {
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;
}
}
library addressSet {
struct _addressSet {
address[] members;
mapping(address => uint) memberIndices;
}
function insert(_addressSet storage self, address other) public {
if (!contains(self, other)) {
assert(length(self) < 2**256-1);
self.members.push(other);
self.memberIndices[other] = length(self);
}
}
function remove(_addressSet storage self, address other) public {
if (contains(self, other)) {
uint replaceIndex = self.memberIndices[other];
address lastMember = self.members[length(self)-1];
// overwrite other with the last member and remove last member
self.members[replaceIndex-1] = lastMember;
self.members.length--;
// reflect this change in the indices
self.memberIndices[lastMember] = replaceIndex;
delete self.memberIndices[other];
}
}
function contains(_addressSet storage self, address other) public view returns (bool) {
return self.memberIndices[other] > 0;
}
function length(_addressSet storage self) public view returns (uint) {
return self.members.length;
}
}
interface ERC20 {
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
interface SnowflakeResolver {
function callOnSignUp() external returns (bool);
function onSignUp(string hydroId, uint allowance) external returns (bool);
function callOnRemoval() external returns (bool);
function onRemoval(string hydroId) external returns(bool);
}
interface ClientRaindrop {
function getUserByAddress(address _address) external view returns (string userName);
function isSigned(
address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s
) external pure returns (bool);
}
interface ViaContract {
function snowflakeCall(address resolver, string hydroIdFrom, string hydroIdTo, uint amount, bytes _bytes) external;
function snowflakeCall(address resolver, string hydroIdFrom, address to, uint amount, bytes _bytes) external;
}
contract Snowflake is Ownable {
using SafeMath for uint;
using addressSet for addressSet._addressSet;
// hydro token wrapper variable
mapping (string => uint) internal deposits;
// signature variables
uint signatureTimeout;
mapping (bytes32 => bool) signatureLog;
// lookup mappings -- accessible only by wrapper functions
mapping (string => Identity) internal directory;
mapping (address => string) internal addressDirectory;
mapping (bytes32 => string) internal initiatedAddressClaims;
// admin/contract variables
address public clientRaindropAddress;
address public hydroTokenAddress;
addressSet._addressSet resolverWhitelist;
constructor() public {
setSignatureTimeout(7200);
}
// identity structures
struct Identity {
address owner;
addressSet._addressSet addresses;
addressSet._addressSet resolvers;
mapping(address => uint) resolverAllowances;
}
// checks whether the given address is owned by a token (does not throw)
function hasToken(address _address) public view returns (bool) {
return bytes(addressDirectory[_address]).length != 0;
}
// enforces that a particular address has a token
modifier _hasToken(address _address, bool check) {
require(hasToken(_address) == check, "The transaction sender does not have a Snowflake.");
_;
}
// gets the HydroID for an address (throws if address doesn't have a HydroID or doesn't have a snowflake)
function getHydroId(address _address) public view returns (string hydroId) {
require(hasToken(_address), "The address does not have a hydroId");
return addressDirectory[_address];
}
// allows whitelisting of resolvers
function whitelistResolver(address resolver) public {
resolverWhitelist.insert(resolver);
emit ResolverWhitelisted(resolver);
}
function isWhitelisted(address resolver) public view returns(bool) {
return resolverWhitelist.contains(resolver);
}
function getWhitelistedResolvers() public view returns(address[]) {
return resolverWhitelist.members;
}
// set the signature timeout
function setSignatureTimeout(uint newTimeout) public {
require(newTimeout >= 1800, "Timeout must be at least 30 minutes.");
require(newTimeout <= 604800, "Timeout must be less than a week.");
signatureTimeout = newTimeout;
}
// set the raindrop and hydro token addresses
function setAddresses(address clientRaindrop, address hydroToken) public onlyOwner {
clientRaindropAddress = clientRaindrop;
hydroTokenAddress = hydroToken;
}
// token minting
function mintIdentityToken() public _hasToken(msg.sender, false) {
_mintIdentityToken(msg.sender);
}
function mintIdentityTokenDelegated(address _address, uint8 v, bytes32 r, bytes32 s)
public _hasToken(_address, false)
{
ClientRaindrop clientRaindrop = ClientRaindrop(clientRaindropAddress);
require(
clientRaindrop.isSigned(
_address, keccak256(abi.encodePacked("Create Snowflake", _address)), v, r, s
),
"Permission denied."
);
_mintIdentityToken(_address);
}
function _mintIdentityToken(address _address) internal {
ClientRaindrop clientRaindrop = ClientRaindrop(clientRaindropAddress);
string memory hydroId = clientRaindrop.getUserByAddress(_address);
Identity storage identity = directory[hydroId];
identity.owner = _address;
identity.addresses.insert(_address);
addressDirectory[_address] = hydroId;
emit SnowflakeMinted(hydroId);
}
// wrappers that enable modifying resolvers
function addResolvers(address[] resolvers, uint[] withdrawAllowances) public _hasToken(msg.sender, true) {
_addResolvers(addressDirectory[msg.sender], resolvers, withdrawAllowances);
}
function addResolversDelegated(
string hydroId, address[] resolvers, uint[] withdrawAllowances, uint8 v, bytes32 r, bytes32 s, uint timestamp
) public
{
require(directory[hydroId].owner != address(0), "Must initiate claim for a HydroID with a Snowflake");
// solium-disable-next-line security/no-block-members
require(timestamp.add(signatureTimeout) > block.timestamp, "Message was signed too long ago.");
ClientRaindrop clientRaindrop = ClientRaindrop(clientRaindropAddress);
require(
clientRaindrop.isSigned(
directory[hydroId].owner,
keccak256(abi.encodePacked("Add Resolvers", resolvers, withdrawAllowances, timestamp)),
v, r, s
),
"Permission denied."
);
_addResolvers(hydroId, resolvers, withdrawAllowances);
}
function _addResolvers(
string hydroId, address[] resolvers, uint[] withdrawAllowances
) internal {
require(resolvers.length == withdrawAllowances.length, "Malformed inputs.");
Identity storage identity = directory[hydroId];
for (uint i; i < resolvers.length; i++) {
require(resolverWhitelist.contains(resolvers[i]), "The given resolver is not on the whitelist.");
require(!identity.resolvers.contains(resolvers[i]), "Snowflake has already set this resolver.");
SnowflakeResolver snowflakeResolver = SnowflakeResolver(resolvers[i]);
identity.resolvers.insert(resolvers[i]);
identity.resolverAllowances[resolvers[i]] = withdrawAllowances[i];
if (snowflakeResolver.callOnSignUp()) {
require(
snowflakeResolver.onSignUp(hydroId, withdrawAllowances[i]),
"Sign up failure."
);
}
emit ResolverAdded(hydroId, resolvers[i], withdrawAllowances[i]);
}
}
function changeResolverAllowances(address[] resolvers, uint[] withdrawAllowances)
public _hasToken(msg.sender, true)
{
_changeResolverAllowances(addressDirectory[msg.sender], resolvers, withdrawAllowances);
}
function changeResolverAllowancesDelegated(
string hydroId, address[] resolvers, uint[] withdrawAllowances, uint8 v, bytes32 r, bytes32 s, uint timestamp
) public
{
require(directory[hydroId].owner != address(0), "Must initiate claim for a HydroID with a Snowflake");
bytes32 _hash = keccak256(
abi.encodePacked("Change Resolver Allowances", resolvers, withdrawAllowances, timestamp)
);
require(signatureLog[_hash] == false, "Signature was already submitted");
signatureLog[_hash] = true;
ClientRaindrop clientRaindrop = ClientRaindrop(clientRaindropAddress);
require(clientRaindrop.isSigned(directory[hydroId].owner, _hash, v, r, s), "Permission denied.");
_changeResolverAllowances(hydroId, resolvers, withdrawAllowances);
}
function _changeResolverAllowances(string hydroId, address[] resolvers, uint[] withdrawAllowances) internal {
require(resolvers.length == withdrawAllowances.length, "Malformed inputs.");
Identity storage identity = directory[hydroId];
for (uint i; i < resolvers.length; i++) {
require(identity.resolvers.contains(resolvers[i]), "Snowflake has not set this resolver.");
identity.resolverAllowances[resolvers[i]] = withdrawAllowances[i];
emit ResolverAllowanceChanged(hydroId, resolvers[i], withdrawAllowances[i]);
}
}
function removeResolvers(address[] resolvers, bool force) public _hasToken(msg.sender, true) {
Identity storage identity = directory[addressDirectory[msg.sender]];
for (uint i; i < resolvers.length; i++) {
require(identity.resolvers.contains(resolvers[i]), "Snowflake has not set this resolver.");
identity.resolvers.remove(resolvers[i]);
delete identity.resolverAllowances[resolvers[i]];
if (!force) {
SnowflakeResolver snowflakeResolver = SnowflakeResolver(resolvers[i]);
if (snowflakeResolver.callOnRemoval()) {
require(
snowflakeResolver.onRemoval(addressDirectory[msg.sender]),
"Removal failure."
);
}
}
emit ResolverRemoved(addressDirectory[msg.sender], resolvers[i]);
}
}
// functions to read token values (does not throw)
function getDetails(string hydroId) public view returns (
address owner,
address[] resolvers,
address[] ownedAddresses,
uint256 balance
) {
Identity storage identity = directory[hydroId];
return (
identity.owner,
identity.resolvers.members,
identity.addresses.members,
deposits[hydroId]
);
}
// check resolver membership (does not throw)
function hasResolver(string hydroId, address resolver) public view returns (bool) {
Identity storage identity = directory[hydroId];
return identity.resolvers.contains(resolver);
}
// check address ownership (does not throw)
function ownsAddress(string hydroId, address _address) public view returns (bool) {
Identity storage identity = directory[hydroId];
return identity.addresses.contains(_address);
}
// check resolver allowances (does not throw)
function getResolverAllowance(string hydroId, address resolver) public view returns (uint withdrawAllowance) {
Identity storage identity = directory[hydroId];
return identity.resolverAllowances[resolver];
}
// allow contract to receive HYDRO tokens
function receiveApproval(address sender, uint amount, address _tokenAddress, bytes _bytes) public {
require(msg.sender == _tokenAddress, "Malformed inputs.");
require(_tokenAddress == hydroTokenAddress, "Sender is not the HYDRO token smart contract.");
address recipient;
if (_bytes.length == 20) {
assembly { // solium-disable-line security/no-inline-assembly
recipient := div(mload(add(add(_bytes, 0x20), 0)), 0x1000000000000000000000000)
}
} else {
recipient = sender;
}
require(hasToken(recipient), "Invalid token recipient");
ERC20 hydro = ERC20(_tokenAddress);
require(hydro.transferFrom(sender, address(this), amount), "Unable to transfer token ownership.");
deposits[addressDirectory[recipient]] = deposits[addressDirectory[recipient]].add(amount);
emit SnowflakeDeposit(addressDirectory[recipient], sender, amount);
}
function snowflakeBalance(string hydroId) public view returns (uint) {
return deposits[hydroId];
}
// transfer snowflake balance from one snowflake holder to another
function transferSnowflakeBalance(string hydroIdTo, uint amount) public _hasToken(msg.sender, true) {
_transfer(addressDirectory[msg.sender], hydroIdTo, amount);
}
// withdraw Snowflake balance to an external address
function withdrawSnowflakeBalance(address to, uint amount) public _hasToken(msg.sender, true) {
_withdraw(addressDirectory[msg.sender], to, amount);
}
// allows resolvers to transfer allowance amounts to other snowflakes (throws if unsuccessful)
function transferSnowflakeBalanceFrom(string hydroIdFrom, string hydroIdTo, uint amount) public {
handleAllowance(hydroIdFrom, amount);
_transfer(hydroIdFrom, hydroIdTo, amount);
}
// allows resolvers to withdraw allowance amounts to external addresses (throws if unsuccessful)
function withdrawSnowflakeBalanceFrom(string hydroIdFrom, address to, uint amount) public {
handleAllowance(hydroIdFrom, amount);
_withdraw(hydroIdFrom, to, amount);
}
// allows resolvers to send withdrawal amounts to arbitrary smart contracts 'to' hydroIds (throws if unsuccessful)
function withdrawSnowflakeBalanceFromVia(
string hydroIdFrom, address via, string hydroIdTo, uint amount, bytes _bytes
) public {
handleAllowance(hydroIdFrom, amount);
_withdraw(hydroIdFrom, via, amount);
ViaContract viaContract = ViaContract(via);
viaContract.snowflakeCall(msg.sender, hydroIdFrom, hydroIdTo, amount, _bytes);
}
// allows resolvers to send withdrawal amounts 'to' addresses via arbitrary smart contracts
function withdrawSnowflakeBalanceFromVia(
string hydroIdFrom, address via, address to, uint amount, bytes _bytes
) public {
handleAllowance(hydroIdFrom, amount);
_withdraw(hydroIdFrom, via, amount);
ViaContract viaContract = ViaContract(via);
viaContract.snowflakeCall(msg.sender, hydroIdFrom, to, amount, _bytes);
}
function _transfer(string hydroIdFrom, string hydroIdTo, uint amount) internal returns (bool) {
require(directory[hydroIdTo].owner != address(0), "Must transfer to an HydroID with a Snowflake");
require(deposits[hydroIdFrom] >= amount, "Cannot withdraw more than the current deposit balance.");
deposits[hydroIdFrom] = deposits[hydroIdFrom].sub(amount);
deposits[hydroIdTo] = deposits[hydroIdTo].add(amount);
emit SnowflakeTransfer(hydroIdFrom, hydroIdTo, amount);
}
function _withdraw(string hydroIdFrom, address to, uint amount) internal {
require(to != address(this), "Cannot transfer to the Snowflake smart contract itself.");
require(deposits[hydroIdFrom] >= amount, "Cannot withdraw more than the current deposit balance.");
deposits[hydroIdFrom] = deposits[hydroIdFrom].sub(amount);
ERC20 hydro = ERC20(hydroTokenAddress);
require(hydro.transfer(to, amount), "Transfer was unsuccessful");
emit SnowflakeWithdraw(to, amount);
}
function handleAllowance(string hydroIdFrom, uint amount) internal {
Identity storage identity = directory[hydroIdFrom];
require(identity.owner != address(0), "Must withdraw from a HydroID with a Snowflake");
// check that resolver-related details are correct
require(identity.resolvers.contains(msg.sender), "Resolver has not been set by from tokenholder.");
if (identity.resolverAllowances[msg.sender] < amount) {
emit InsufficientAllowance(hydroIdFrom, msg.sender, identity.resolverAllowances[msg.sender], amount);
require(false, "Insufficient Allowance");
}
identity.resolverAllowances[msg.sender] = identity.resolverAllowances[msg.sender].sub(amount);
}
// address ownership functions
// to claim an address, users need to send a transaction from their snowflake address containing a sealed claim
// sealedClaims are: keccak256(abi.encodePacked(<address>, <secret>, <hydroId>)),
// where <address> is the address you'd like to claim, and <secret> is a SECRET bytes32 value.
function initiateClaimDelegated(string hydroId, bytes32 sealedClaim, uint8 v, bytes32 r, bytes32 s) public {
require(directory[hydroId].owner != address(0), "Must initiate claim for a HydroID with a Snowflake");
ClientRaindrop clientRaindrop = ClientRaindrop(clientRaindropAddress);
require(
clientRaindrop.isSigned(
directory[hydroId].owner, keccak256(abi.encodePacked("Initiate Claim", sealedClaim)), v, r, s
),
"Permission denied."
);
_initiateClaim(hydroId, sealedClaim);
}
function initiateClaim(bytes32 sealedClaim) public _hasToken(msg.sender, true) {
_initiateClaim(addressDirectory[msg.sender], sealedClaim);
}
function _initiateClaim(string hydroId, bytes32 sealedClaim) internal {
require(bytes(initiatedAddressClaims[sealedClaim]).length == 0, "This sealed claim has been submitted.");
initiatedAddressClaims[sealedClaim] = hydroId;
}
function finalizeClaim(bytes32 secret, string hydroId) public {
bytes32 possibleSealedClaim = keccak256(abi.encodePacked(msg.sender, secret, hydroId));
require(
bytes(initiatedAddressClaims[possibleSealedClaim]).length != 0, "This sealed claim hasn't been submitted."
);
// ensure that the claim wasn't stolen by another HydroID during initialization
require(
keccak256(abi.encodePacked(initiatedAddressClaims[possibleSealedClaim])) ==
keccak256(abi.encodePacked(hydroId)),
"Invalid signature."
);
directory[hydroId].addresses.insert(msg.sender);
addressDirectory[msg.sender] = hydroId;
emit AddressClaimed(msg.sender, hydroId);
}
function unclaim(address[] addresses) public _hasToken(msg.sender, true) {
for (uint i; i < addresses.length; i++) {
require(addresses[i] != directory[addressDirectory[msg.sender]].owner, "Cannot unclaim owner address.");
directory[addressDirectory[msg.sender]].addresses.remove(addresses[i]);
delete addressDirectory[addresses[i]];
emit AddressUnclaimed(addresses[i], addressDirectory[msg.sender]);
}
}
// events
event SnowflakeMinted(string hydroId);
event ResolverWhitelisted(address indexed resolver);
event ResolverAdded(string hydroId, address resolver, uint withdrawAllowance);
event ResolverAllowanceChanged(string hydroId, address resolver, uint withdrawAllowance);
event ResolverRemoved(string hydroId, address resolver);
event SnowflakeDeposit(string hydroId, address from, uint amount);
event SnowflakeTransfer(string hydroIdFrom, string hydroIdTo, uint amount);
event SnowflakeWithdraw(address to, uint amount);
event InsufficientAllowance(
string hydroId, address indexed resolver, uint currentAllowance, uint requestedWithdraw
);
event AddressClaimed(address indexed _address, string hydroId);
event AddressUnclaimed(address indexed _address, string hydroId);
} | check resolver membership (does not throw) | function hasResolver(string hydroId, address resolver) public view returns (bool) {
Identity storage identity = directory[hydroId];
return identity.resolvers.contains(resolver);
}
| 5,536,581 | [
1,
1893,
5039,
12459,
261,
20657,
486,
604,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
711,
4301,
12,
1080,
4855,
9005,
548,
16,
1758,
5039,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
7808,
2502,
4215,
273,
1867,
63,
18112,
9005,
548,
15533,
203,
3639,
327,
4215,
18,
7818,
2496,
18,
12298,
12,
14122,
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
]
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "hardhat/console.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "./BullsToTheMoonInterface.sol";
/**
* @notice ENS registry to get chainlink resolver
*/
interface ENS {
function resolver(bytes32) external view returns (Resolver);
}
/**
* @notice Chainlink resolver to get price feed proxy
*/
interface Resolver {
function addr(bytes32) external view returns (address);
}
/**
* @title Bulls (dynamic NFTs) that grow with rising price
* @author Justa Liang
*/
contract BullsToTheMoon is ERC721Enumerable, BullsToTheMoonInterface {
/// @notice Counter of bullId
uint public counter;
/// @notice ENS interface (fixed address)
ENS public ens;
/// @dev Bull's state
struct Bull {
address proxy; // which proxy of Chainlink price feed
bool closed; // position closed
int latestPrice; // latest updated price from Chainlink
int roi; // return on investment
}
/// @dev Bull's profile for viewing
struct BullProfile {
address proxy;
bool closed;
int latestPrice;
int roi;
string uri;
}
/// @dev Bull's state stored on-chain
mapping(uint => Bull) public bullStateOf;
/// @notice Emit when a bull's state changes
event BullState(
uint indexed bullId,
address indexed proxy,
bool indexed closed,
int latestPrice,
int roi
);
/**
* @dev Set name, symbol, and addresses of interactive contracts
*/
constructor(address ensRegistryAddr)
ERC721("BullsToTheMoon", "B2M")
{
counter = 0;
ens = ENS(ensRegistryAddr);
}
/**
* @dev Check the owner
*/
modifier checkOwner(uint bullId) {
require(
_isApprovedOrOwner(_msgSender(), bullId),
"wrong owner"
);
_;
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function open(uint bullId) override external checkOwner(bullId) {
Bull storage target = bullStateOf[bullId];
require(
target.closed,
"bull already opened"
);
// get current price
AggregatorV3Interface pricefeed = AggregatorV3Interface(target.proxy);
(,int currPrice,,,) = pricefeed.latestRoundData();
// update on-chain data
target.latestPrice = currPrice;
target.closed = false;
// emit bull state
emit BullState(bullId, target.proxy, false, currPrice, target.roi);
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function close(uint bullId) override external checkOwner(bullId) {
Bull storage target = bullStateOf[bullId];
require(
!target.closed,
"bull already closed"
);
// get current price
AggregatorV3Interface pricefeed = AggregatorV3Interface(target.proxy);
(,int currPrice,,,) = pricefeed.latestRoundData();
// update on-chain data
target.roi = currPrice*(10000+target.roi)/target.latestPrice-10000;
target.closed = true;
// emit bull state
emit BullState(bullId, target.proxy, true, currPrice, target.roi);
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function breed(bytes32 namehash) override external returns (uint) {
address proxyAddr = _resolve(namehash);
require(
proxyAddr != address(0),
"invalid proxy"
);
// get current price
AggregatorV3Interface pricefeed = AggregatorV3Interface(proxyAddr);
(,int currPrice,,,) = pricefeed.latestRoundData();
// mint bull and store its state on chain
uint newId = counter;
_safeMint(_msgSender(), newId);
bullStateOf[newId] = Bull(proxyAddr, false, currPrice, 0);
emit BullState(newId, proxyAddr, false, currPrice, 0);
counter++;
return newId;
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function regretOpen(uint bullId) override external checkOwner(bullId) {
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function regretClose(uint bullId) override external checkOwner(bullId) {
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function occupy(uint bullId, uint fieldId) override external checkOwner(bullId) {
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function vote(uint proposalId, uint fieldCount) override external {
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function propose(string memory proposedBaseURI) override external {
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function startVote() override external {
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function endVote() override external {
}
/**
* @dev Resolve ENS-namehash to Chainlink price feed proxy
*/
function _resolve(bytes32 node) internal view returns (address) {
Resolver resolver = ens.resolver(node);
return resolver.addr(node);
}
}
| * @notice Chainlink resolver to get price feed proxy/ | interface Resolver {
function addr(bytes32) external view returns (address);
}
| 926,528 | [
1,
3893,
1232,
5039,
358,
336,
6205,
4746,
2889,
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,
5831,
17183,
288,
203,
565,
445,
3091,
12,
3890,
1578,
13,
3903,
1476,
1135,
261,
2867,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/97/0x65d02A3481F3c25DE96671E30044fad2D060ae95/sources/project:/contracts/Exchange/exchange.sol | * @dev Creates a sell order @param order - Object of sell order. @param signature. Emits a {OrderCreated} event, indicating the order, unique key and the signer./ saleType and tokenType validation startTime and endTime validation verify signature get unique key existing order validation update order status | function createOrder(LibOrder.Order memory order, bytes calldata signature) external whenNotPaused nonReentrant {
require(!blacklisted[msg.sender], "Exchange: Blackisted");
require(order.tokenType == ASSET_TYPE_ERC721 || order.tokenType == ASSET_TYPE_ERC1155, "Exchange: Invalid token type");
require(order.saleType == FIXED_SALE_CLASS || order.saleType == CLOSED_AUCTION_SALE_CLASS || order.saleType == OPEN_AUCTION_SALE_CLASS, "Exchange: Invalid sale type");
if(order.saleType == CLOSED_AUCTION_SALE_CLASS || order.saleType == OPEN_AUCTION_SALE_CLASS)
require(order.startTime > block.timestamp, "Exchange: start time must be greater than current time");
if(order.saleType == CLOSED_AUCTION_SALE_CLASS) require(order.endTime > order.startTime, "Exchange: end time must be greater than start time");
bytes32 structHash = LibOrder._genOrderHash(order);
bytes32 hashTypedData = _hashTypedDataV4(structHash);
address signer = _verifySignature(hashTypedData, signature);
require(signer == order.seller, "Exchange: Order is not signed by the seller");
bytes32 hashKey = LibOrder._genHashKey(order);
require(OrderStatus[hashKey] == 0x00000000, "Exchange: Order already exists");
OrderStatus[hashKey] = NEW_ORDER_CLASS;
emit OrderCreated(order, hashKey, signer);
}
| 3,276,154 | [
1,
2729,
279,
357,
80,
1353,
225,
1353,
300,
1033,
434,
357,
80,
1353,
18,
225,
3372,
18,
7377,
1282,
279,
288,
2448,
6119,
97,
871,
16,
11193,
326,
1353,
16,
3089,
498,
471,
326,
10363,
18,
19,
272,
5349,
559,
471,
22302,
3379,
8657,
471,
13859,
3379,
3929,
3372,
336,
3089,
498,
2062,
1353,
3379,
1089,
1353,
1267,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
752,
2448,
12,
5664,
2448,
18,
2448,
3778,
1353,
16,
1731,
745,
892,
3372,
13,
3903,
1347,
1248,
28590,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
12,
5,
11223,
18647,
63,
3576,
18,
15330,
6487,
315,
11688,
30,
22467,
25444,
8863,
203,
203,
3639,
2583,
12,
1019,
18,
2316,
559,
422,
5355,
4043,
67,
2399,
67,
654,
39,
27,
5340,
747,
1353,
18,
2316,
559,
422,
5355,
4043,
67,
2399,
67,
654,
39,
2499,
2539,
16,
315,
11688,
30,
1962,
1147,
618,
8863,
203,
3639,
2583,
12,
1019,
18,
87,
5349,
559,
422,
26585,
67,
5233,
900,
67,
5237,
747,
1353,
18,
87,
5349,
559,
422,
27160,
67,
14237,
3106,
67,
5233,
900,
67,
5237,
747,
1353,
18,
87,
5349,
559,
422,
11919,
67,
14237,
3106,
67,
5233,
900,
67,
5237,
16,
315,
11688,
30,
1962,
272,
5349,
618,
8863,
203,
203,
3639,
309,
12,
1019,
18,
87,
5349,
559,
422,
27160,
67,
14237,
3106,
67,
5233,
900,
67,
5237,
747,
1353,
18,
87,
5349,
559,
422,
11919,
67,
14237,
3106,
67,
5233,
900,
67,
5237,
13,
203,
5411,
2583,
12,
1019,
18,
1937,
950,
405,
1203,
18,
5508,
16,
315,
11688,
30,
787,
813,
1297,
506,
6802,
2353,
783,
813,
8863,
203,
3639,
309,
12,
1019,
18,
87,
5349,
559,
422,
27160,
67,
14237,
3106,
67,
5233,
900,
67,
5237,
13,
2583,
12,
1019,
18,
409,
950,
405,
1353,
18,
1937,
950,
16,
315,
11688,
30,
679,
813,
1297,
506,
6802,
2353,
787,
813,
8863,
203,
203,
3639,
1731,
1578,
2
]
|
./full_match/5/0xf2b3aEc131b7df040B1190CceA1754872A7e3ee5/sources/NftStaking.sol | this updates when a user withdraws or stake more nfts
| uint256 lastTimeUpdated; | 1,861,787 | [
1,
2211,
4533,
1347,
279,
729,
598,
9446,
87,
578,
384,
911,
1898,
290,
1222,
87,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
377,
2254,
5034,
31323,
7381,
31,
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,
-100
]
|
./full_match/1/0x9D35B7afFf83Fd7EA2c9ed16E1C08af27aC07D18/sources/contracts/AliumRouter.sol | 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, 'AliumLibrary: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'AliumLibrary: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(10_000);
uint denominator = reserveOut.sub(amountOut).mul(9_975);
amountIn = (numerator / denominator).add(1);
}
| 9,653,698 | [
1,
10822,
392,
876,
3844,
434,
392,
3310,
471,
3082,
400,
264,
3324,
16,
1135,
279,
1931,
810,
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
]
| [
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,
445,
24418,
382,
12,
11890,
3844,
1182,
16,
2254,
20501,
382,
16,
2254,
20501,
1182,
13,
2713,
16618,
1135,
261,
11890,
3844,
382,
13,
288,
203,
3639,
2583,
12,
8949,
1182,
405,
374,
16,
296,
37,
549,
379,
9313,
30,
2120,
6639,
42,
1653,
7266,
2222,
67,
15527,
67,
2192,
51,
5321,
8284,
203,
3639,
2583,
12,
455,
6527,
382,
405,
374,
597,
20501,
1182,
405,
374,
16,
296,
37,
549,
379,
9313,
30,
2120,
6639,
42,
1653,
7266,
2222,
67,
2053,
53,
3060,
4107,
8284,
203,
3639,
2254,
16730,
273,
20501,
382,
18,
16411,
12,
8949,
1182,
2934,
16411,
12,
2163,
67,
3784,
1769,
203,
3639,
2254,
15030,
273,
20501,
1182,
18,
1717,
12,
8949,
1182,
2934,
16411,
12,
29,
67,
29,
5877,
1769,
203,
3639,
3844,
382,
273,
261,
2107,
7385,
342,
15030,
2934,
1289,
12,
21,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.24;
import 'zeppelin-solidity/contracts/ownership/Ownable.sol';
contract MemberRegistry is Ownable {
struct Member {
address owner;
bytes12 name; // up to 12 characters, guaranteed unique
bytes32 profileIPFS; // this will point to image, blurb, profile, etc
// this is not efficiently packed yet
bool exiled;
}
mapping (address => Member) public addressMap;
mapping (bytes32 => address) public usernameMap;
mapping (address => address) public proxyMap;
function privilegedCreate(address _owner, bytes12 _name, bytes32 _profileIPFS)
public onlyOwner
{
createInternal(_owner, _name, _profileIPFS);
}
function create(bytes12 _name, bytes32 _profileIPFS)
public
{
createInternal(msg.sender, _name, _profileIPFS);
}
function createInternal(address _owner, bytes12 _name, bytes32 _profileIPFS)
internal
{
// ensure this name isn't empty
require(_name != '');
// ensure this name isn't already taken
require (usernameMap[_name] == 0);
// ensure this address has not been registered yet
require (addressMap[_owner].owner == 0x0);
Member memory newMember = Member(
{
owner: _owner,
name: _name,
profileIPFS: _profileIPFS,
exiled: false
});
usernameMap[_name] = _owner;
addressMap[_owner] = newMember;
}
// function setProxy(address _newOwner)
// public
// {
// require(addressMap[msg.sender].owner > 0);
// proxyMap[_newOwner] = msg.sender;
// }
function setProfile(bytes32 _profileIPFS)
public
{
if (proxyMap[msg.sender] > 0) {
address proxied = proxyMap[msg.sender];
addressMap[proxied].profileIPFS = _profileIPFS;
} else {
addressMap[msg.sender].profileIPFS = _profileIPFS;
}
}
function exile(address _owner)
public onlyOwner
{
if (proxyMap[_owner] > 0) {
address proxied = proxyMap[_owner];
addressMap[proxied].exiled = true;
} else {
addressMap[_owner].exiled = true;
}
}
function get(address _owner)
public view
returns (address owner_, bytes16 name_, bytes32 profileIPFS_, bool exiled_)
{
if (proxyMap[_owner] > 0) {
address proxied = proxyMap[_owner];
return (addressMap[proxied].owner, addressMap[proxied].name, addressMap[proxied].profileIPFS, addressMap[proxied].exiled);
} else {
return (addressMap[_owner].owner, addressMap[_owner].name, addressMap[_owner].profileIPFS, addressMap[_owner].exiled);
}
}
}
// ability to upgrade without losing data | this will point to image, blurb, profile, etc
| bytes32 profileIPFS; | 6,382,651 | [
1,
2211,
903,
1634,
358,
1316,
16,
2811,
15850,
16,
3042,
16,
5527,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3639,
1731,
1578,
3042,
2579,
4931,
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
]
|
// Contracts by dYdX Foundation. Individual files are released under different licenses.
//
// https://dydx.community
// https://github.com/dydxfoundation/governance-contracts
//
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../dependencies/open-zeppelin/SafeERC20.sol';
import { IERC20 } from '../../interfaces/IERC20.sol';
import { SM1Admin } from '../v1_1/impl/SM1Admin.sol';
import { SM1Getters } from '../v1_1/impl/SM1Getters.sol';
import { SM1Operators } from '../v1_1/impl/SM1Operators.sol';
import { SM1Slashing } from '../v1_1/impl/SM1Slashing.sol';
import { SM1Staking } from '../v1_1/impl/SM1Staking.sol';
/**
* @title SafetyModuleV2
* @author dYdX
*
* @notice Contract for staking tokens, which may be slashed by the permissioned slasher.
*
* NOTE: Most functions will revert if epoch zero has not started.
*/
contract SafetyModuleV2 is
SM1Slashing,
SM1Operators,
SM1Admin,
SM1Getters
{
using SafeERC20 for IERC20;
// ============ Constants ============
string public constant EIP712_DOMAIN_NAME = 'dYdX Safety Module';
string public constant EIP712_DOMAIN_VERSION = '1';
bytes32 public constant EIP712_DOMAIN_SCHEMA_HASH = keccak256(
'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'
);
// ============ Constructor ============
constructor(
IERC20 stakedToken,
IERC20 rewardsToken,
address rewardsTreasury,
uint256 distributionStart,
uint256 distributionEnd
)
SM1Staking(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd)
{}
// ============ External Functions ============
/**
* @notice Initializer for v2, intended to fix the deployment bug that affected v1.
*
* Responsible for the following:
*
* 1. Funds recovery and staker compensation:
* - Transfer all Safety Module DYDX to the recovery contract.
* - Transfer compensation amount from the rewards treasury to the recovery contract.
*
* 2. Storage recovery and cleanup:
* - Set the _EXCHANGE_RATE_ to EXCHANGE_RATE_BASE.
* - Clean up invalid storage values at slots 115 and 125.
*
* @param recoveryContract The address of the contract which will distribute
* recovered funds to stakers.
* @param recoveryCompensationAmount Amount to transfer out of the rewards treasury, for staker
* compensation, on top of the return of staked funds.
*/
function initialize(
address recoveryContract,
uint256 recoveryCompensationAmount
)
external
initializer
{
// Funds recovery and staker compensation.
uint256 balance = STAKED_TOKEN.balanceOf(address(this));
STAKED_TOKEN.safeTransfer(recoveryContract, balance);
REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recoveryContract, recoveryCompensationAmount);
// Storage recovery and cleanup.
__SM1ExchangeRate_init();
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(115, 0)
sstore(125, 0)
}
}
// ============ Internal Functions ============
/**
* @dev Returns the revision of the implementation contract.
*
* @return The revision number.
*/
function getRevision()
internal
pure
override
returns (uint256)
{
return 2;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import { IERC20 } from '../../interfaces/IERC20.sol';
import { SafeMath } from './SafeMath.sol';
import { Address } from './Address.sol';
/**
* @title SafeERC20
* @dev From https://github.com/OpenZeppelin/openzeppelin-contracts
* Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
'SafeERC20: approve from non-zero to non-zero allowance'
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), 'SafeERC20: call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, 'SafeERC20: low-level call failed');
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed');
}
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1Roles } from './SM1Roles.sol';
import { SM1StakedBalances } from './SM1StakedBalances.sol';
/**
* @title SM1Admin
* @author dYdX
*
* @dev Admin-only functions.
*/
abstract contract SM1Admin is
SM1StakedBalances,
SM1Roles
{
using SafeMath for uint256;
// ============ External Functions ============
/**
* @notice Set the parameters defining the function from timestamp to epoch number.
*
* The formula used is `n = floor((t - b) / a)` where:
* - `n` is the epoch number
* - `t` is the timestamp (in seconds)
* - `b` is a non-negative offset, indicating the start of epoch zero (in seconds)
* - `a` is the length of an epoch, a.k.a. the interval (in seconds)
*
* Reverts if epoch zero already started, and the new parameters would change the current epoch.
* Reverts if epoch zero has not started, but would have had started under the new parameters.
*
* @param interval The length `a` of an epoch, in seconds.
* @param offset The offset `b`, i.e. the start of epoch zero, in seconds.
*/
function setEpochParameters(
uint256 interval,
uint256 offset
)
external
onlyRole(EPOCH_PARAMETERS_ROLE)
nonReentrant
{
if (!hasEpochZeroStarted()) {
require(
block.timestamp < offset,
'SM1Admin: Started epoch zero'
);
_setEpochParameters(interval, offset);
return;
}
// We must settle the total active balance to ensure the index is recorded at the epoch
// boundary as needed, before we make any changes to the epoch formula.
_settleTotalActiveBalance();
// Update the epoch parameters. Require that the current epoch number is unchanged.
uint256 originalCurrentEpoch = getCurrentEpoch();
_setEpochParameters(interval, offset);
uint256 newCurrentEpoch = getCurrentEpoch();
require(
originalCurrentEpoch == newCurrentEpoch,
'SM1Admin: Changed epochs'
);
}
/**
* @notice Set the blackout window, during which one cannot request withdrawals of staked funds.
*/
function setBlackoutWindow(
uint256 blackoutWindow
)
external
onlyRole(EPOCH_PARAMETERS_ROLE)
nonReentrant
{
_setBlackoutWindow(blackoutWindow);
}
/**
* @notice Set the emission rate of rewards.
*
* @param emissionPerSecond The new number of rewards tokens given out per second.
*/
function setRewardsPerSecond(
uint256 emissionPerSecond
)
external
onlyRole(REWARDS_RATE_ROLE)
nonReentrant
{
uint256 totalStaked = 0;
if (hasEpochZeroStarted()) {
// We must settle the total active balance to ensure the index is recorded at the epoch
// boundary as needed, before we make any changes to the emission rate.
totalStaked = _settleTotalActiveBalance();
}
_setRewardsPerSecond(emissionPerSecond, totalStaked);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { Math } from '../../../utils/Math.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1Storage } from './SM1Storage.sol';
/**
* @title SM1Getters
* @author dYdX
*
* @dev Some external getter functions.
*/
abstract contract SM1Getters is
SM1Storage
{
using SafeMath for uint256;
// ============ External Functions ============
/**
* @notice The parameters specifying the function from timestamp to epoch number.
*
* @return The parameters struct with `interval` and `offset` fields.
*/
function getEpochParameters()
external
view
returns (SM1Types.EpochParameters memory)
{
return _EPOCH_PARAMETERS_;
}
/**
* @notice The period of time at the end of each epoch in which withdrawals cannot be requested.
*
* @return The blackout window duration, in seconds.
*/
function getBlackoutWindow()
external
view
returns (uint256)
{
return _BLACKOUT_WINDOW_;
}
/**
* @notice Get the domain separator used for EIP-712 signatures.
*
* @return The EIP-712 domain separator.
*/
function getDomainSeparator()
external
view
returns (bytes32)
{
return _DOMAIN_SEPARATOR_;
}
/**
* @notice The value of one underlying token, in the units used for staked balances, denominated
* as a mutiple of EXCHANGE_RATE_BASE for additional precision.
*
* To convert from an underlying amount to a staked amount, multiply by the exchange rate.
*
* @return The exchange rate.
*/
function getExchangeRate()
external
view
returns (uint256)
{
return _EXCHANGE_RATE_;
}
/**
* @notice Get an exchange rate snapshot.
*
* @param index The index number of the exchange rate snapshot.
*
* @return The snapshot struct with `blockNumber` and `value` fields.
*/
function getExchangeRateSnapshot(
uint256 index
)
external
view
returns (SM1Types.Snapshot memory)
{
return _EXCHANGE_RATE_SNAPSHOTS_[index];
}
/**
* @notice Get the number of exchange rate snapshots.
*
* @return The number of snapshots that have been taken of the exchange rate.
*/
function getExchangeRateSnapshotCount()
external
view
returns (uint256)
{
return _EXCHANGE_RATE_SNAPSHOT_COUNT_;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { SM1Roles } from './SM1Roles.sol';
import { SM1Staking } from './SM1Staking.sol';
/**
* @title SM1Operators
* @author dYdX
*
* @dev Actions which may be called by authorized operators, nominated by the contract owner.
*
* There are two types of operators. These should be smart contracts, which can be used to
* provide additional functionality to users:
*
* STAKE_OPERATOR_ROLE:
*
* This operator is allowed to request withdrawals and withdraw funds on behalf of stakers. This
* role could be used by a smart contract to provide a staking interface with additional
* features, for example, optional lock-up periods that pay out additional rewards (from a
* separate rewards pool).
*
* CLAIM_OPERATOR_ROLE:
*
* This operator is allowed to claim rewards on behalf of stakers. This role could be used by a
* smart contract to provide an interface for claiming rewards from multiple incentive programs
* at once.
*/
abstract contract SM1Operators is
SM1Staking,
SM1Roles
{
using SafeMath for uint256;
// ============ Events ============
event OperatorStakedFor(
address indexed staker,
uint256 amount,
address operator
);
event OperatorWithdrawalRequestedFor(
address indexed staker,
uint256 amount,
address operator
);
event OperatorWithdrewStakeFor(
address indexed staker,
address recipient,
uint256 amount,
address operator
);
event OperatorClaimedRewardsFor(
address indexed staker,
address recipient,
uint256 claimedRewards,
address operator
);
// ============ External Functions ============
/**
* @notice Request a withdrawal on behalf of a staker.
*
* Reverts if we are currently in the blackout window.
*
* @param staker The staker whose stake to request a withdrawal for.
* @param stakeAmount The amount of stake to move from the active to the inactive balance.
*/
function requestWithdrawalFor(
address staker,
uint256 stakeAmount
)
external
onlyRole(STAKE_OPERATOR_ROLE)
nonReentrant
{
_requestWithdrawal(staker, stakeAmount);
emit OperatorWithdrawalRequestedFor(staker, stakeAmount, msg.sender);
}
/**
* @notice Withdraw a staker's stake, and send to the specified recipient.
*
* @param staker The staker whose stake to withdraw.
* @param recipient The address that should receive the funds.
* @param stakeAmount The amount of stake to withdraw from the staker's inactive balance.
*/
function withdrawStakeFor(
address staker,
address recipient,
uint256 stakeAmount
)
external
onlyRole(STAKE_OPERATOR_ROLE)
nonReentrant
{
_withdrawStake(staker, recipient, stakeAmount);
emit OperatorWithdrewStakeFor(staker, recipient, stakeAmount, msg.sender);
}
/**
* @notice Claim rewards on behalf of a staker, and send them to the specified recipient.
*
* @param staker The staker whose rewards to claim.
* @param recipient The address that should receive the funds.
*
* @return The number of rewards tokens claimed.
*/
function claimRewardsFor(
address staker,
address recipient
)
external
onlyRole(CLAIM_OPERATOR_ROLE)
nonReentrant
returns (uint256)
{
uint256 rewards = _settleAndClaimRewards(staker, recipient); // Emits an event internally.
emit OperatorClaimedRewardsFor(staker, recipient, rewards, msg.sender);
return rewards;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol';
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { Math } from '../../../utils/Math.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1Roles } from './SM1Roles.sol';
import { SM1Staking } from './SM1Staking.sol';
/**
* @title SM1Slashing
* @author dYdX
*
* @dev Provides the slashing function for removing funds from the contract.
*
* SLASHING:
*
* All funds in the contract, active or inactive, are slashable. Slashes are recorded by updating
* the exchange rate, and to simplify the technical implementation, we disallow full slashes.
* To reduce the possibility of overflow in the exchange rate, we place an upper bound on the
* fraction of funds that may be slashed in a single slash.
*
* Warning: Slashing is not possible if the slash would cause the exchange rate to overflow.
*
* REWARDS AND GOVERNANCE POWER ACCOUNTING:
*
* Since all slashes are accounted for by a global exchange rate, slashes do not require any
* update to staked balances. The earning of rewards is unaffected by slashes.
*
* Governance power takes slashes into account by using snapshots of the exchange rate inside
* the getPowerAtBlock() function. Note that getPowerAtBlock() returns the governance power as of
* the end of the specified block.
*/
abstract contract SM1Slashing is
SM1Staking,
SM1Roles
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ============ Constants ============
/// @notice The maximum fraction of funds that may be slashed in a single slash (numerator).
uint256 public constant MAX_SLASH_NUMERATOR = 95;
/// @notice The maximum fraction of funds that may be slashed in a single slash (denominator).
uint256 public constant MAX_SLASH_DENOMINATOR = 100;
// ============ Events ============
event Slashed(
uint256 amount,
address recipient,
uint256 newExchangeRate
);
// ============ External Functions ============
/**
* @notice Slash staked token balances and withdraw those funds to the specified address.
*
* @param requestedSlashAmount The request slash amount, denominated in the underlying token.
* @param recipient The address to receive the slashed tokens.
*
* @return The amount slashed, denominated in the underlying token.
*/
function slash(
uint256 requestedSlashAmount,
address recipient
)
external
onlyRole(SLASHER_ROLE)
nonReentrant
returns (uint256)
{
uint256 underlyingBalance = STAKED_TOKEN.balanceOf(address(this));
if (underlyingBalance == 0) {
return 0;
}
// Get the slash amount and remaining amount. Note that remainingAfterSlash is nonzero.
uint256 maxSlashAmount = underlyingBalance.mul(MAX_SLASH_NUMERATOR).div(MAX_SLASH_DENOMINATOR);
uint256 slashAmount = Math.min(requestedSlashAmount, maxSlashAmount);
uint256 remainingAfterSlash = underlyingBalance.sub(slashAmount);
if (slashAmount == 0) {
return 0;
}
// Update the exchange rate.
//
// Warning: Can revert if the max exchange rate is exceeded.
uint256 newExchangeRate = updateExchangeRate(underlyingBalance, remainingAfterSlash);
// Transfer the slashed token.
STAKED_TOKEN.safeTransfer(recipient, slashAmount);
emit Slashed(slashAmount, recipient, newExchangeRate);
return slashAmount;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol';
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { Math } from '../../../utils/Math.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1ERC20 } from './SM1ERC20.sol';
import { SM1StakedBalances } from './SM1StakedBalances.sol';
/**
* @title SM1Staking
* @author dYdX
*
* @dev External functions for stakers. See SM1StakedBalances for details on staker accounting.
*
* UNDERLYING AND STAKED AMOUNTS:
*
* We distinguish between underlying amounts and stake amounts. An underlying amount is denoted
* in the original units of the token being staked. A stake amount is adjusted by the exchange
* rate, which can increase due to slashing. Before any slashes have occurred, the exchange rate
* is equal to one.
*/
abstract contract SM1Staking is
SM1StakedBalances,
SM1ERC20
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ============ Events ============
event Staked(
address indexed staker,
address spender,
uint256 underlyingAmount,
uint256 stakeAmount
);
event WithdrawalRequested(
address indexed staker,
uint256 stakeAmount
);
event WithdrewStake(
address indexed staker,
address recipient,
uint256 underlyingAmount,
uint256 stakeAmount
);
// ============ Constants ============
IERC20 public immutable STAKED_TOKEN;
// ============ Constructor ============
constructor(
IERC20 stakedToken,
IERC20 rewardsToken,
address rewardsTreasury,
uint256 distributionStart,
uint256 distributionEnd
)
SM1StakedBalances(rewardsToken, rewardsTreasury, distributionStart, distributionEnd)
{
STAKED_TOKEN = stakedToken;
}
// ============ External Functions ============
/**
* @notice Deposit and stake funds. These funds are active and start earning rewards immediately.
*
* @param underlyingAmount The amount of underlying token to stake.
*/
function stake(
uint256 underlyingAmount
)
external
nonReentrant
{
_stake(msg.sender, underlyingAmount);
}
/**
* @notice Deposit and stake on behalf of another address.
*
* @param staker The staker who will receive the stake.
* @param underlyingAmount The amount of underlying token to stake.
*/
function stakeFor(
address staker,
uint256 underlyingAmount
)
external
nonReentrant
{
_stake(staker, underlyingAmount);
}
/**
* @notice Request to withdraw funds. Starting in the next epoch, the funds will be “inactive”
* and available for withdrawal. Inactive funds do not earn rewards.
*
* Reverts if we are currently in the blackout window.
*
* @param stakeAmount The amount of stake to move from the active to the inactive balance.
*/
function requestWithdrawal(
uint256 stakeAmount
)
external
nonReentrant
{
_requestWithdrawal(msg.sender, stakeAmount);
}
/**
* @notice Withdraw the sender's inactive funds, and send to the specified recipient.
*
* @param recipient The address that should receive the funds.
* @param stakeAmount The amount of stake to withdraw from the sender's inactive balance.
*/
function withdrawStake(
address recipient,
uint256 stakeAmount
)
external
nonReentrant
{
_withdrawStake(msg.sender, recipient, stakeAmount);
}
/**
* @notice Withdraw the max available inactive funds, and send to the specified recipient.
*
* This is less gas-efficient than querying the max via eth_call and calling withdrawStake().
*
* @param recipient The address that should receive the funds.
*
* @return The withdrawn amount.
*/
function withdrawMaxStake(
address recipient
)
external
nonReentrant
returns (uint256)
{
uint256 stakeAmount = getStakeAvailableToWithdraw(msg.sender);
_withdrawStake(msg.sender, recipient, stakeAmount);
return stakeAmount;
}
/**
* @notice Settle and claim all rewards, and send them to the specified recipient.
*
* Call this function with eth_call to query the claimable rewards balance.
*
* @param recipient The address that should receive the funds.
*
* @return The number of rewards tokens claimed.
*/
function claimRewards(
address recipient
)
external
nonReentrant
returns (uint256)
{
return _settleAndClaimRewards(msg.sender, recipient); // Emits an event internally.
}
// ============ Public Functions ============
/**
* @notice Get the amount of stake available for a given staker to withdraw.
*
* @param staker The address whose balance to check.
*
* @return The staker's stake amount that is inactive and available to withdraw.
*/
function getStakeAvailableToWithdraw(
address staker
)
public
view
returns (uint256)
{
// Note that the next epoch inactive balance is always at least that of the current epoch.
return getInactiveBalanceCurrentEpoch(staker);
}
// ============ Internal Functions ============
function _stake(
address staker,
uint256 underlyingAmount
)
internal
{
// Convert using the exchange rate.
uint256 stakeAmount = stakeAmountFromUnderlyingAmount(underlyingAmount);
// Update staked balances and delegate snapshots.
_increaseCurrentAndNextActiveBalance(staker, stakeAmount);
_moveDelegatesForTransfer(address(0), staker, stakeAmount);
// Transfer token from the sender.
STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), underlyingAmount);
emit Staked(staker, msg.sender, underlyingAmount, stakeAmount);
emit Transfer(address(0), msg.sender, stakeAmount);
}
function _requestWithdrawal(
address staker,
uint256 stakeAmount
)
internal
{
require(
!inBlackoutWindow(),
'SM1Staking: Withdraw requests restricted in the blackout window'
);
// Get the staker's requestable amount and revert if there is not enough to request withdrawal.
uint256 requestableBalance = getActiveBalanceNextEpoch(staker);
require(
stakeAmount <= requestableBalance,
'SM1Staking: Withdraw request exceeds next active balance'
);
// Move amount from active to inactive in the next epoch.
_moveNextBalanceActiveToInactive(staker, stakeAmount);
emit WithdrawalRequested(staker, stakeAmount);
}
function _withdrawStake(
address staker,
address recipient,
uint256 stakeAmount
)
internal
{
// Get staker withdrawable balance and revert if there is not enough to withdraw.
uint256 withdrawableBalance = getInactiveBalanceCurrentEpoch(staker);
require(
stakeAmount <= withdrawableBalance,
'SM1Staking: Withdraw amount exceeds staker inactive balance'
);
// Update staked balances and delegate snapshots.
_decreaseCurrentAndNextInactiveBalance(staker, stakeAmount);
_moveDelegatesForTransfer(staker, address(0), stakeAmount);
// Convert using the exchange rate.
uint256 underlyingAmount = underlyingAmountFromStakeAmount(stakeAmount);
// Transfer token to the recipient.
STAKED_TOKEN.safeTransfer(recipient, underlyingAmount);
emit Transfer(msg.sender, address(0), stakeAmount);
emit WithdrewStake(staker, recipient, underlyingAmount, stakeAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'SafeMath: addition overflow');
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, 'SafeMath: subtraction overflow');
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, 'SafeMath: multiplication overflow');
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, 'SafeMath: division by zero');
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, 'SafeMath: modulo by zero');
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, 'Address: insufficient balance');
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}('');
require(success, 'Address: unable to send value, recipient may have reverted');
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
library SM1Types {
/**
* @dev The parameters used to convert a timestamp to an epoch number.
*/
struct EpochParameters {
uint128 interval;
uint128 offset;
}
/**
* @dev Snapshot of a value at a specific block, used to track historical governance power.
*/
struct Snapshot {
uint256 blockNumber;
uint256 value;
}
/**
* @dev A balance, possibly with a change scheduled for the next epoch.
*
* @param currentEpoch The epoch in which the balance was last updated.
* @param currentEpochBalance The balance at epoch `currentEpoch`.
* @param nextEpochBalance The balance at epoch `currentEpoch + 1`.
*/
struct StoredBalance {
uint16 currentEpoch;
uint240 currentEpochBalance;
uint240 nextEpochBalance;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SM1Storage } from './SM1Storage.sol';
/**
* @title SM1Roles
* @author dYdX
*
* @dev Defines roles used in the SafetyModuleV1 contract. The hierarchy of roles and powers
* of each role are described below.
*
* Roles:
*
* OWNER_ROLE
* | -> May add or remove addresses from any of the roles below.
* |
* +-- SLASHER_ROLE
* | -> Can slash staked token balances and withdraw those funds.
* |
* +-- EPOCH_PARAMETERS_ROLE
* | -> May set epoch parameters such as the interval, offset, and blackout window.
* |
* +-- REWARDS_RATE_ROLE
* | -> May set the emission rate of rewards.
* |
* +-- CLAIM_OPERATOR_ROLE
* | -> May claim rewards on behalf of a user.
* |
* +-- STAKE_OPERATOR_ROLE
* -> May manipulate user's staked funds (e.g. perform withdrawals on behalf of a user).
*/
abstract contract SM1Roles is SM1Storage {
bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE');
bytes32 public constant SLASHER_ROLE = keccak256('SLASHER_ROLE');
bytes32 public constant EPOCH_PARAMETERS_ROLE = keccak256('EPOCH_PARAMETERS_ROLE');
bytes32 public constant REWARDS_RATE_ROLE = keccak256('REWARDS_RATE_ROLE');
bytes32 public constant CLAIM_OPERATOR_ROLE = keccak256('CLAIM_OPERATOR_ROLE');
bytes32 public constant STAKE_OPERATOR_ROLE = keccak256('STAKE_OPERATOR_ROLE');
function __SM1Roles_init() internal {
// Assign roles to the sender.
//
// The STAKE_OPERATOR_ROLE and CLAIM_OPERATOR_ROLE roles are not initially assigned.
// These can be assigned to other smart contracts to provide additional functionality for users.
_setupRole(OWNER_ROLE, msg.sender);
_setupRole(SLASHER_ROLE, msg.sender);
_setupRole(EPOCH_PARAMETERS_ROLE, msg.sender);
_setupRole(REWARDS_RATE_ROLE, msg.sender);
// Set OWNER_ROLE as the admin of all roles.
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
_setRoleAdmin(SLASHER_ROLE, OWNER_ROLE);
_setRoleAdmin(EPOCH_PARAMETERS_ROLE, OWNER_ROLE);
_setRoleAdmin(REWARDS_RATE_ROLE, OWNER_ROLE);
_setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE);
_setRoleAdmin(STAKE_OPERATOR_ROLE, OWNER_ROLE);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { SafeCast } from '../lib/SafeCast.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1Rewards } from './SM1Rewards.sol';
/**
* @title SM1StakedBalances
* @author dYdX
*
* @dev Accounting of staked balances.
*
* NOTE: Functions may revert if epoch zero has not started.
*
* NOTE: All amounts dealt with in this file are denominated in staked units, which because of the
* exchange rate, may not correspond one-to-one with the underlying token. See SM1Staking.sol.
*
* STAKED BALANCE ACCOUNTING:
*
* A staked balance is in one of two states:
* - active: Earning staking rewards; cannot be withdrawn by staker; may be slashed.
* - inactive: Not earning rewards; can be withdrawn by the staker; may be slashed.
*
* A staker may have a combination of active and inactive balances. The following operations
* affect staked balances as follows:
* - deposit: Increase active balance.
* - request withdrawal: At the end of the current epoch, move some active funds to inactive.
* - withdraw: Decrease inactive balance.
* - transfer: Move some active funds to another staker.
*
* To encode the fact that a balance may be scheduled to change at the end of a certain epoch, we
* store each balance as a struct of three fields: currentEpoch, currentEpochBalance, and
* nextEpochBalance.
*
* REWARDS ACCOUNTING:
*
* Active funds earn rewards for the period of time that they remain active. This means, after
* requesting a withdrawal of some funds, those funds will continue to earn rewards until the end
* of the epoch. For example:
*
* epoch: n n + 1 n + 2 n + 3
* | | | |
* +----------+----------+----------+-----...
* ^ t_0: User makes a deposit.
* ^ t_1: User requests a withdrawal of all funds.
* ^ t_2: The funds change state from active to inactive.
*
* In the above scenario, the user would earn rewards for the period from t_0 to t_2, varying
* with the total staked balance in that period. If the user only request a withdrawal for a part
* of their balance, then the remaining balance would continue earning rewards beyond t_2.
*
* User rewards must be settled via SM1Rewards any time a user's active balance changes. Special
* attention is paid to the the epoch boundaries, where funds may have transitioned from active
* to inactive.
*
* SETTLEMENT DETAILS:
*
* Internally, this module uses the following types of operations on stored balances:
* - Load: Loads a balance, while applying settlement logic internally to get the
* up-to-date result. Returns settlement results without updating state.
* - Store: Stores a balance.
* - Load-for-update: Performs a load and applies updates as needed to rewards accounting.
* Since this is state-changing, it must be followed by a store operation.
* - Settle: Performs load-for-update and store operations.
*
* This module is responsible for maintaining the following invariants to ensure rewards are
* calculated correctly:
* - When an active balance is loaded for update, if a rollover occurs from one epoch to the
* next, the rewards index must be settled up to the boundary at which the rollover occurs.
* - Because the global rewards index is needed to update the user rewards index, the total
* active balance must be settled before any staker balances are settled or loaded for update.
* - A staker's balance must be settled before their rewards are settled.
*/
abstract contract SM1StakedBalances is
SM1Rewards
{
using SafeCast for uint256;
using SafeMath for uint256;
// ============ Constructor ============
constructor(
IERC20 rewardsToken,
address rewardsTreasury,
uint256 distributionStart,
uint256 distributionEnd
)
SM1Rewards(rewardsToken, rewardsTreasury, distributionStart, distributionEnd)
{}
// ============ Public Functions ============
/**
* @notice Get the current active balance of a staker.
*/
function getActiveBalanceCurrentEpoch(
address staker
)
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
(SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(
_ACTIVE_BALANCES_[staker]
);
return uint256(balance.currentEpochBalance);
}
/**
* @notice Get the next epoch active balance of a staker.
*/
function getActiveBalanceNextEpoch(
address staker
)
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
(SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(
_ACTIVE_BALANCES_[staker]
);
return uint256(balance.nextEpochBalance);
}
/**
* @notice Get the current total active balance.
*/
function getTotalActiveBalanceCurrentEpoch()
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
(SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(
_TOTAL_ACTIVE_BALANCE_
);
return uint256(balance.currentEpochBalance);
}
/**
* @notice Get the next epoch total active balance.
*/
function getTotalActiveBalanceNextEpoch()
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
(SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(
_TOTAL_ACTIVE_BALANCE_
);
return uint256(balance.nextEpochBalance);
}
/**
* @notice Get the current inactive balance of a staker.
* @dev The balance is converted via the index to token units.
*/
function getInactiveBalanceCurrentEpoch(
address staker
)
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
SM1Types.StoredBalance memory balance = _loadInactiveBalance(_INACTIVE_BALANCES_[staker]);
return uint256(balance.currentEpochBalance);
}
/**
* @notice Get the next epoch inactive balance of a staker.
* @dev The balance is converted via the index to token units.
*/
function getInactiveBalanceNextEpoch(
address staker
)
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
SM1Types.StoredBalance memory balance = _loadInactiveBalance(_INACTIVE_BALANCES_[staker]);
return uint256(balance.nextEpochBalance);
}
/**
* @notice Get the current total inactive balance.
*/
function getTotalInactiveBalanceCurrentEpoch()
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
SM1Types.StoredBalance memory balance = _loadInactiveBalance(_TOTAL_INACTIVE_BALANCE_);
return uint256(balance.currentEpochBalance);
}
/**
* @notice Get the next epoch total inactive balance.
*/
function getTotalInactiveBalanceNextEpoch()
public
view
returns (uint256)
{
if (!hasEpochZeroStarted()) {
return 0;
}
SM1Types.StoredBalance memory balance = _loadInactiveBalance(_TOTAL_INACTIVE_BALANCE_);
return uint256(balance.nextEpochBalance);
}
/**
* @notice Get the current transferable balance for a user. The user can
* only transfer their balance that is not currently inactive or going to be
* inactive in the next epoch. Note that this means the user's transferable funds
* are their active balance of the next epoch.
*
* @param account The account to get the transferable balance of.
*
* @return The user's transferable balance.
*/
function getTransferableBalance(
address account
)
public
view
returns (uint256)
{
return getActiveBalanceNextEpoch(account);
}
// ============ Internal Functions ============
function _increaseCurrentAndNextActiveBalance(
address staker,
uint256 amount
)
internal
{
// Always settle total active balance before settling a staker active balance.
uint256 oldTotalBalance = _increaseCurrentAndNextBalances(address(0), true, amount);
uint256 oldUserBalance = _increaseCurrentAndNextBalances(staker, true, amount);
// When an active balance changes at current timestamp, settle rewards to the current timestamp.
_settleUserRewardsUpToNow(staker, oldUserBalance, oldTotalBalance);
}
function _moveNextBalanceActiveToInactive(
address staker,
uint256 amount
)
internal
{
// Decrease the active balance for the next epoch.
// Always settle total active balance before settling a staker active balance.
_decreaseNextBalance(address(0), true, amount);
_decreaseNextBalance(staker, true, amount);
// Increase the inactive balance for the next epoch.
_increaseNextBalance(address(0), false, amount);
_increaseNextBalance(staker, false, amount);
// Note that we don't need to settle rewards since the current active balance did not change.
}
function _transferCurrentAndNextActiveBalance(
address sender,
address recipient,
uint256 amount
)
internal
{
// Always settle total active balance before settling a staker active balance.
uint256 totalBalance = _settleTotalActiveBalance();
// Move current and next active balances from sender to recipient.
uint256 oldSenderBalance = _decreaseCurrentAndNextBalances(sender, true, amount);
uint256 oldRecipientBalance = _increaseCurrentAndNextBalances(recipient, true, amount);
// When an active balance changes at current timestamp, settle rewards to the current timestamp.
_settleUserRewardsUpToNow(sender, oldSenderBalance, totalBalance);
_settleUserRewardsUpToNow(recipient, oldRecipientBalance, totalBalance);
}
function _decreaseCurrentAndNextInactiveBalance(
address staker,
uint256 amount
)
internal
{
// Decrease the inactive balance for the next epoch.
_decreaseCurrentAndNextBalances(address(0), false, amount);
_decreaseCurrentAndNextBalances(staker, false, amount);
// Note that we don't settle rewards since active balances are not affected.
}
function _settleTotalActiveBalance()
internal
returns (uint256)
{
return _settleBalance(address(0), true);
}
function _settleAndClaimRewards(
address staker,
address recipient
)
internal
returns (uint256)
{
// Always settle total active balance before settling a staker active balance.
uint256 totalBalance = _settleTotalActiveBalance();
// Always settle staker active balance before settling staker rewards.
uint256 userBalance = _settleBalance(staker, true);
// Settle rewards balance since we want to claim the full accrued amount.
_settleUserRewardsUpToNow(staker, userBalance, totalBalance);
// Claim rewards balance.
return _claimRewards(staker, recipient);
}
// ============ Private Functions ============
/**
* @dev Load a balance for update and then store it.
*/
function _settleBalance(
address maybeStaker,
bool isActiveBalance
)
private
returns (uint256)
{
SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance);
SM1Types.StoredBalance memory balance =
_loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance);
uint256 currentBalance = uint256(balance.currentEpochBalance);
_storeBalance(balancePtr, balance);
return currentBalance;
}
/**
* @dev Settle a balance while applying an increase.
*/
function _increaseCurrentAndNextBalances(
address maybeStaker,
bool isActiveBalance,
uint256 amount
)
private
returns (uint256)
{
SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance);
SM1Types.StoredBalance memory balance =
_loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance);
uint256 originalCurrentBalance = uint256(balance.currentEpochBalance);
balance.currentEpochBalance = originalCurrentBalance.add(amount).toUint240();
balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240();
_storeBalance(balancePtr, balance);
return originalCurrentBalance;
}
/**
* @dev Settle a balance while applying a decrease.
*/
function _decreaseCurrentAndNextBalances(
address maybeStaker,
bool isActiveBalance,
uint256 amount
)
private
returns (uint256)
{
SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance);
SM1Types.StoredBalance memory balance =
_loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance);
uint256 originalCurrentBalance = uint256(balance.currentEpochBalance);
balance.currentEpochBalance = originalCurrentBalance.sub(amount).toUint240();
balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240();
_storeBalance(balancePtr, balance);
return originalCurrentBalance;
}
/**
* @dev Settle a balance while applying an increase.
*/
function _increaseNextBalance(
address maybeStaker,
bool isActiveBalance,
uint256 amount
)
private
{
SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance);
SM1Types.StoredBalance memory balance =
_loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance);
balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240();
_storeBalance(balancePtr, balance);
}
/**
* @dev Settle a balance while applying a decrease.
*/
function _decreaseNextBalance(
address maybeStaker,
bool isActiveBalance,
uint256 amount
)
private
{
SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance);
SM1Types.StoredBalance memory balance =
_loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance);
balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240();
_storeBalance(balancePtr, balance);
}
function _getBalancePtr(
address maybeStaker,
bool isActiveBalance
)
private
view
returns (SM1Types.StoredBalance storage)
{
// Active.
if (isActiveBalance) {
if (maybeStaker != address(0)) {
return _ACTIVE_BALANCES_[maybeStaker];
}
return _TOTAL_ACTIVE_BALANCE_;
}
// Inactive.
if (maybeStaker != address(0)) {
return _INACTIVE_BALANCES_[maybeStaker];
}
return _TOTAL_INACTIVE_BALANCE_;
}
/**
* @dev Load a balance for updating.
*
* IMPORTANT: This function may modify state, and so the balance MUST be stored afterwards.
* - For active balances:
* - If a rollover occurs, rewards are settled up to the epoch boundary.
*
* @param balancePtr A storage pointer to the balance.
* @param maybeStaker The user address, or address(0) to update total balance.
* @param isActiveBalance Whether the balance is an active balance.
*/
function _loadBalanceForUpdate(
SM1Types.StoredBalance storage balancePtr,
address maybeStaker,
bool isActiveBalance
)
private
returns (SM1Types.StoredBalance memory)
{
// Active balance.
if (isActiveBalance) {
(
SM1Types.StoredBalance memory balance,
uint256 beforeRolloverEpoch,
uint256 beforeRolloverBalance,
bool didRolloverOccur
) = _loadActiveBalance(balancePtr);
if (didRolloverOccur) {
// Handle the effect of the balance rollover on rewards. We must partially settle the index
// up to the epoch boundary where the change in balance occurred. We pass in the balance
// from before the boundary.
if (maybeStaker == address(0)) {
// If it's the total active balance...
_settleGlobalIndexUpToEpoch(beforeRolloverBalance, beforeRolloverEpoch);
} else {
// If it's a user active balance...
_settleUserRewardsUpToEpoch(maybeStaker, beforeRolloverBalance, beforeRolloverEpoch);
}
}
return balance;
}
// Inactive balance.
return _loadInactiveBalance(balancePtr);
}
function _loadActiveBalance(
SM1Types.StoredBalance storage balancePtr
)
private
view
returns (
SM1Types.StoredBalance memory,
uint256,
uint256,
bool
)
{
SM1Types.StoredBalance memory balance = balancePtr;
// Return these as they may be needed for rewards settlement.
uint256 beforeRolloverEpoch = uint256(balance.currentEpoch);
uint256 beforeRolloverBalance = uint256(balance.currentEpochBalance);
bool didRolloverOccur = false;
// Roll the balance forward if needed.
uint256 currentEpoch = getCurrentEpoch();
if (currentEpoch > uint256(balance.currentEpoch)) {
didRolloverOccur = balance.currentEpochBalance != balance.nextEpochBalance;
balance.currentEpoch = currentEpoch.toUint16();
balance.currentEpochBalance = balance.nextEpochBalance;
}
return (balance, beforeRolloverEpoch, beforeRolloverBalance, didRolloverOccur);
}
function _loadInactiveBalance(
SM1Types.StoredBalance storage balancePtr
)
private
view
returns (SM1Types.StoredBalance memory)
{
SM1Types.StoredBalance memory balance = balancePtr;
// Roll the balance forward if needed.
uint256 currentEpoch = getCurrentEpoch();
if (currentEpoch > uint256(balance.currentEpoch)) {
balance.currentEpoch = currentEpoch.toUint16();
balance.currentEpochBalance = balance.nextEpochBalance;
}
return balance;
}
/**
* @dev Store a balance.
*/
function _storeBalance(
SM1Types.StoredBalance storage balancePtr,
SM1Types.StoredBalance memory balance
)
private
{
// Note: This should use a single `sstore` when compiler optimizations are enabled.
balancePtr.currentEpoch = balance.currentEpoch;
balancePtr.currentEpochBalance = balance.currentEpochBalance;
balancePtr.nextEpochBalance = balance.nextEpochBalance;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import {
AccessControlUpgradeable
} from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol';
import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol';
import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol';
import { SM1Types } from '../lib/SM1Types.sol';
/**
* @title SM1Storage
* @author dYdX
*
* @dev Storage contract. Contains or inherits from all contract with storage.
*/
abstract contract SM1Storage is
AccessControlUpgradeable,
ReentrancyGuard,
VersionedInitializable
{
// ============ Epoch Schedule ============
/// @dev The parameters specifying the function from timestamp to epoch number.
SM1Types.EpochParameters internal _EPOCH_PARAMETERS_;
/// @dev The period of time at the end of each epoch in which withdrawals cannot be requested.
uint256 internal _BLACKOUT_WINDOW_;
// ============ Staked Token ERC20 ============
/// @dev Allowances for ERC-20 transfers.
mapping(address => mapping(address => uint256)) internal _ALLOWANCES_;
// ============ Governance Power Delegation ============
/// @dev Domain separator for EIP-712 signatures.
bytes32 internal _DOMAIN_SEPARATOR_;
/// @dev Mapping from (owner) => (next valid nonce) for EIP-712 signatures.
mapping(address => uint256) internal _NONCES_;
/// @dev Snapshots and delegates for governance voting power.
mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _VOTING_SNAPSHOTS_;
mapping(address => uint256) internal _VOTING_SNAPSHOT_COUNTS_;
mapping(address => address) internal _VOTING_DELEGATES_;
/// @dev Snapshots and delegates for governance proposition power.
mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _PROPOSITION_SNAPSHOTS_;
mapping(address => uint256) internal _PROPOSITION_SNAPSHOT_COUNTS_;
mapping(address => address) internal _PROPOSITION_DELEGATES_;
// ============ Rewards Accounting ============
/// @dev The emission rate of rewards.
uint256 internal _REWARDS_PER_SECOND_;
/// @dev The cumulative rewards earned per staked token. (Shared storage slot.)
uint224 internal _GLOBAL_INDEX_;
/// @dev The timestamp at which the global index was last updated. (Shared storage slot.)
uint32 internal _GLOBAL_INDEX_TIMESTAMP_;
/// @dev The value of the global index when the user's staked balance was last updated.
mapping(address => uint256) internal _USER_INDEXES_;
/// @dev The user's accrued, unclaimed rewards (as of the last update to the user index).
mapping(address => uint256) internal _USER_REWARDS_BALANCES_;
/// @dev The value of the global index at the end of a given epoch.
mapping(uint256 => uint256) internal _EPOCH_INDEXES_;
// ============ Staker Accounting ============
/// @dev The active balance by staker.
mapping(address => SM1Types.StoredBalance) internal _ACTIVE_BALANCES_;
/// @dev The total active balance of stakers.
SM1Types.StoredBalance internal _TOTAL_ACTIVE_BALANCE_;
/// @dev The inactive balance by staker.
mapping(address => SM1Types.StoredBalance) internal _INACTIVE_BALANCES_;
/// @dev The total inactive balance of stakers.
SM1Types.StoredBalance internal _TOTAL_INACTIVE_BALANCE_;
// ============ Exchange Rate ============
/// @dev The value of one underlying token, in the units used for staked balances, denominated
/// as a mutiple of EXCHANGE_RATE_BASE for additional precision.
uint256 internal _EXCHANGE_RATE_;
/// @dev Historical snapshots of the exchange rate, in each block that it has changed.
mapping(uint256 => SM1Types.Snapshot) internal _EXCHANGE_RATE_SNAPSHOTS_;
/// @dev Number of snapshots of the exchange rate.
uint256 internal _EXCHANGE_RATE_SNAPSHOT_COUNT_;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import './Context.sol';
import './Strings.sol';
import './ERC165.sol';
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Context, IAccessControlUpgradeable, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(
bytes32 indexed role,
bytes32 indexed previousAdminRole,
bytes32 indexed newAdminRole
);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(IAccessControlUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
'AccessControl: account ',
Strings.toHexString(uint160(account), 20),
' is missing role ',
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account)
public
virtual
override
onlyRole(getRoleAdmin(role))
{
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account)
public
virtual
override
onlyRole(getRoleAdmin(role))
{
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), 'AccessControl: can only renounce roles for self');
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title ReentrancyGuard
* @author dYdX
*
* @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts.
*/
abstract contract ReentrancyGuard {
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = uint256(int256(-1));
uint256 private _STATUS_;
constructor()
internal
{
_STATUS_ = NOT_ENTERED;
}
modifier nonReentrant() {
require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call');
_STATUS_ = ENTERED;
_;
_STATUS_ = NOT_ENTERED;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
/**
* @title VersionedInitializable
* @author Aave, inspired by the OpenZeppelin Initializable contract
*
* @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.
*
*/
abstract contract VersionedInitializable {
/**
* @dev Indicates that the contract has been initialized.
*/
uint256 internal lastInitializedRevision = 0;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
uint256 revision = getRevision();
require(revision > lastInitializedRevision, "Contract instance has already been initialized");
lastInitializedRevision = revision;
_;
}
/// @dev returns the revision number of the contract.
/// Needs to be defined in the inherited class as a constant.
function getRevision() internal pure virtual returns(uint256);
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/*
* @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.7.5;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = '0123456789abcdef';
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return '0';
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return '0x00';
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = '0';
buffer[1] = 'x';
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, 'Strings: hex length insufficient');
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import './IERC165.sol';
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @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: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @dev Methods for downcasting unsigned integers, reverting on overflow.
*/
library SafeCast {
/**
* @dev Downcast to a uint16, reverting on overflow.
*/
function toUint16(
uint256 a
)
internal
pure
returns (uint16)
{
uint16 b = uint16(a);
require(
uint256(b) == a,
'SafeCast: toUint16 overflow'
);
return b;
}
/**
* @dev Downcast to a uint32, reverting on overflow.
*/
function toUint32(
uint256 a
)
internal
pure
returns (uint32)
{
uint32 b = uint32(a);
require(
uint256(b) == a,
'SafeCast: toUint32 overflow'
);
return b;
}
/**
* @dev Downcast to a uint128, reverting on overflow.
*/
function toUint128(
uint256 a
)
internal
pure
returns (uint128)
{
uint128 b = uint128(a);
require(
uint256(b) == a,
'SafeCast: toUint128 overflow'
);
return b;
}
/**
* @dev Downcast to a uint224, reverting on overflow.
*/
function toUint224(
uint256 a
)
internal
pure
returns (uint224)
{
uint224 b = uint224(a);
require(
uint256(b) == a,
'SafeCast: toUint224 overflow'
);
return b;
}
/**
* @dev Downcast to a uint240, reverting on overflow.
*/
function toUint240(
uint256 a
)
internal
pure
returns (uint240)
{
uint240 b = uint240(a);
require(
uint256(b) == a,
'SafeCast: toUint240 overflow'
);
return b;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol';
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { Math } from '../../../utils/Math.sol';
import { SafeCast } from '../lib/SafeCast.sol';
import { SM1EpochSchedule } from './SM1EpochSchedule.sol';
/**
* @title SM1Rewards
* @author dYdX
*
* @dev Manages the distribution of token rewards.
*
* Rewards are distributed continuously. After each second, an account earns rewards `r` according
* to the following formula:
*
* r = R * s / S
*
* Where:
* - `R` is the rewards distributed globally each second, also called the “emission rate.”
* - `s` is the account's staked balance in that second (technically, it is measured at the
* end of the second)
* - `S` is the sum total of all staked balances in that second (again, measured at the end of
* the second)
*
* The parameter `R` can be configured by the contract owner. For every second that elapses,
* exactly `R` tokens will accrue to users, save for rounding errors, and with the exception that
* while the total staked balance is zero, no tokens will accrue to anyone.
*
* The accounting works as follows: A global index is stored which represents the cumulative
* number of rewards tokens earned per staked token since the start of the distribution.
* The value of this index increases over time, and there are two factors affecting the rate of
* increase:
* 1) The emission rate (in the numerator)
* 2) The total number of staked tokens (in the denominator)
*
* Whenever either factor changes, in some timestamp T, we settle the global index up to T by
* calculating the increase in the index since the last update using the OLD values of the factors:
*
* indexDelta = timeDelta * emissionPerSecond * INDEX_BASE / totalStaked
*
* Where `INDEX_BASE` is a scaling factor used to allow more precision in the storage of the index.
*
* For each user we store an accrued rewards balance, as well as a user index, which is a cache of
* the global index at the time that the user's accrued rewards balance was last updated. Then at
* any point in time, a user's claimable rewards are represented by the following:
*
* rewards = _USER_REWARDS_BALANCES_[user] + userStaked * (
* settledGlobalIndex - _USER_INDEXES_[user]
* ) / INDEX_BASE
*/
abstract contract SM1Rewards is
SM1EpochSchedule
{
using SafeCast for uint256;
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ============ Constants ============
/// @dev Additional precision used to represent the global and user index values.
uint256 private constant INDEX_BASE = 10**18;
/// @notice The rewards token.
IERC20 public immutable REWARDS_TOKEN;
/// @notice Address to pull rewards from. Must have provided an allowance to this contract.
address public immutable REWARDS_TREASURY;
/// @notice Start timestamp (inclusive) of the period in which rewards can be earned.
uint256 public immutable DISTRIBUTION_START;
/// @notice End timestamp (exclusive) of the period in which rewards can be earned.
uint256 public immutable DISTRIBUTION_END;
// ============ Events ============
event RewardsPerSecondUpdated(
uint256 emissionPerSecond
);
event GlobalIndexUpdated(
uint256 index
);
event UserIndexUpdated(
address indexed user,
uint256 index,
uint256 unclaimedRewards
);
event ClaimedRewards(
address indexed user,
address recipient,
uint256 claimedRewards
);
// ============ Constructor ============
constructor(
IERC20 rewardsToken,
address rewardsTreasury,
uint256 distributionStart,
uint256 distributionEnd
) {
require(
distributionEnd >= distributionStart,
'SM1Rewards: Invalid parameters'
);
REWARDS_TOKEN = rewardsToken;
REWARDS_TREASURY = rewardsTreasury;
DISTRIBUTION_START = distributionStart;
DISTRIBUTION_END = distributionEnd;
}
// ============ External Functions ============
/**
* @notice The current emission rate of rewards.
*
* @return The number of rewards tokens issued globally each second.
*/
function getRewardsPerSecond()
external
view
returns (uint256)
{
return _REWARDS_PER_SECOND_;
}
// ============ Internal Functions ============
/**
* @dev Initialize the contract.
*/
function __SM1Rewards_init()
internal
{
_GLOBAL_INDEX_TIMESTAMP_ = Math.max(block.timestamp, DISTRIBUTION_START).toUint32();
}
/**
* @dev Set the emission rate of rewards.
*
* IMPORTANT: Do not call this function without settling the total staked balance first, to
* ensure that the index is settled up to the epoch boundaries.
*
* @param emissionPerSecond The new number of rewards tokens to give out each second.
* @param totalStaked The total staked balance.
*/
function _setRewardsPerSecond(
uint256 emissionPerSecond,
uint256 totalStaked
)
internal
{
_settleGlobalIndexUpToNow(totalStaked);
_REWARDS_PER_SECOND_ = emissionPerSecond;
emit RewardsPerSecondUpdated(emissionPerSecond);
}
/**
* @dev Claim tokens, sending them to the specified recipient.
*
* Note: In order to claim all accrued rewards, the total and user staked balances must first be
* settled before calling this function.
*
* @param user The user's address.
* @param recipient The address to send rewards to.
*
* @return The number of rewards tokens claimed.
*/
function _claimRewards(
address user,
address recipient
)
internal
returns (uint256)
{
uint256 accruedRewards = _USER_REWARDS_BALANCES_[user];
_USER_REWARDS_BALANCES_[user] = 0;
REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recipient, accruedRewards);
emit ClaimedRewards(user, recipient, accruedRewards);
return accruedRewards;
}
/**
* @dev Settle a user's rewards up to the latest global index as of `block.timestamp`. Triggers a
* settlement of the global index up to `block.timestamp`. Should be called with the OLD user
* and total balances.
*
* @param user The user's address.
* @param userStaked Tokens staked by the user during the period since the last user index
* update.
* @param totalStaked Total tokens staked by all users during the period since the last global
* index update.
*
* @return The user's accrued rewards, including past unclaimed rewards.
*/
function _settleUserRewardsUpToNow(
address user,
uint256 userStaked,
uint256 totalStaked
)
internal
returns (uint256)
{
uint256 globalIndex = _settleGlobalIndexUpToNow(totalStaked);
return _settleUserRewardsUpToIndex(user, userStaked, globalIndex);
}
/**
* @dev Settle a user's rewards up to an epoch boundary. Should be used to partially settle a
* user's rewards if their balance was known to have changed on that epoch boundary.
*
* @param user The user's address.
* @param userStaked Tokens staked by the user. Should be accurate for the time period
* since the last update to this user and up to the end of the
* specified epoch.
* @param epochNumber Settle the user's rewards up to the end of this epoch.
*
* @return The user's accrued rewards, including past unclaimed rewards, up to the end of the
* specified epoch.
*/
function _settleUserRewardsUpToEpoch(
address user,
uint256 userStaked,
uint256 epochNumber
)
internal
returns (uint256)
{
uint256 globalIndex = _EPOCH_INDEXES_[epochNumber];
return _settleUserRewardsUpToIndex(user, userStaked, globalIndex);
}
/**
* @dev Settle the global index up to the end of the given epoch.
*
* IMPORTANT: This function should only be called under conditions which ensure the following:
* - `epochNumber` < the current epoch number
* - `_GLOBAL_INDEX_TIMESTAMP_ < settleUpToTimestamp`
* - `_EPOCH_INDEXES_[epochNumber] = 0`
*/
function _settleGlobalIndexUpToEpoch(
uint256 totalStaked,
uint256 epochNumber
)
internal
returns (uint256)
{
uint256 settleUpToTimestamp = getStartOfEpoch(epochNumber.add(1));
uint256 globalIndex = _settleGlobalIndexUpToTimestamp(totalStaked, settleUpToTimestamp);
_EPOCH_INDEXES_[epochNumber] = globalIndex;
return globalIndex;
}
// ============ Private Functions ============
/**
* @dev Updates the global index, reflecting cumulative rewards given out per staked token.
*
* @param totalStaked The total staked balance, which should be constant in the interval
* since the last update to the global index.
*
* @return The new global index.
*/
function _settleGlobalIndexUpToNow(
uint256 totalStaked
)
private
returns (uint256)
{
return _settleGlobalIndexUpToTimestamp(totalStaked, block.timestamp);
}
/**
* @dev Helper function which settles a user's rewards up to a global index. Should be called
* any time a user's staked balance changes, with the OLD user and total balances.
*
* @param user The user's address.
* @param userStaked Tokens staked by the user during the period since the last user index
* update.
* @param newGlobalIndex The new index value to bring the user index up to. MUST NOT be less
* than the user's index.
*
* @return The user's accrued rewards, including past unclaimed rewards.
*/
function _settleUserRewardsUpToIndex(
address user,
uint256 userStaked,
uint256 newGlobalIndex
)
private
returns (uint256)
{
uint256 oldAccruedRewards = _USER_REWARDS_BALANCES_[user];
uint256 oldUserIndex = _USER_INDEXES_[user];
if (oldUserIndex == newGlobalIndex) {
return oldAccruedRewards;
}
uint256 newAccruedRewards;
if (userStaked == 0) {
// Note: Even if the user's staked balance is zero, we still need to update the user index.
newAccruedRewards = oldAccruedRewards;
} else {
// Calculate newly accrued rewards since the last update to the user's index.
uint256 indexDelta = newGlobalIndex.sub(oldUserIndex);
uint256 accruedRewardsDelta = userStaked.mul(indexDelta).div(INDEX_BASE);
newAccruedRewards = oldAccruedRewards.add(accruedRewardsDelta);
// Update the user's rewards.
_USER_REWARDS_BALANCES_[user] = newAccruedRewards;
}
// Update the user's index.
_USER_INDEXES_[user] = newGlobalIndex;
emit UserIndexUpdated(user, newGlobalIndex, newAccruedRewards);
return newAccruedRewards;
}
/**
* @dev Updates the global index, reflecting cumulative rewards given out per staked token.
*
* @param totalStaked The total staked balance, which should be constant in the interval
* (_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp).
* @param settleUpToTimestamp The timestamp up to which to settle rewards. It MUST satisfy
* `settleUpToTimestamp <= block.timestamp`.
*
* @return The new global index.
*/
function _settleGlobalIndexUpToTimestamp(
uint256 totalStaked,
uint256 settleUpToTimestamp
)
private
returns (uint256)
{
uint256 oldGlobalIndex = uint256(_GLOBAL_INDEX_);
// The goal of this function is to calculate rewards earned since the last global index update.
// These rewards are earned over the time interval which is the intersection of the intervals
// [_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp] and [DISTRIBUTION_START, DISTRIBUTION_END].
//
// We can simplify a bit based on the assumption:
// `_GLOBAL_INDEX_TIMESTAMP_ >= DISTRIBUTION_START`
//
// Get the start and end of the time interval under consideration.
uint256 intervalStart = uint256(_GLOBAL_INDEX_TIMESTAMP_);
uint256 intervalEnd = Math.min(settleUpToTimestamp, DISTRIBUTION_END);
// Return early if the interval has length zero (incl. case where intervalEnd < intervalStart).
if (intervalEnd <= intervalStart) {
return oldGlobalIndex;
}
// Note: If we reach this point, we must update _GLOBAL_INDEX_TIMESTAMP_.
uint256 emissionPerSecond = _REWARDS_PER_SECOND_;
if (emissionPerSecond == 0 || totalStaked == 0) {
// Ensure a log is emitted if the timestamp changed, even if the index does not change.
_GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32();
emit GlobalIndexUpdated(oldGlobalIndex);
return oldGlobalIndex;
}
// Calculate the change in index over the interval.
uint256 timeDelta = intervalEnd.sub(intervalStart);
uint256 indexDelta = timeDelta.mul(emissionPerSecond).mul(INDEX_BASE).div(totalStaked);
// Calculate, update, and return the new global index.
uint256 newGlobalIndex = oldGlobalIndex.add(indexDelta);
// Update storage. (Shared storage slot.)
_GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32();
_GLOBAL_INDEX_ = newGlobalIndex.toUint224();
emit GlobalIndexUpdated(newGlobalIndex);
return newGlobalIndex;
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol';
/**
* @title Math
* @author dYdX
*
* @dev Library for non-standard Math functions.
*/
library Math {
using SafeMath for uint256;
// ============ Library Functions ============
/**
* @dev Return `ceil(numerator / denominator)`.
*/
function divRoundUp(
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
if (numerator == 0) {
// SafeMath will check for zero denominator
return SafeMath.div(0, denominator);
}
return numerator.sub(1).div(denominator).add(1);
}
/**
* @dev Returns the minimum between a and b.
*/
function min(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
/**
* @dev Returns the maximum between a and b.
*/
function max(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a > b ? a : b;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { SafeCast } from '../lib/SafeCast.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1Storage } from './SM1Storage.sol';
/**
* @title SM1EpochSchedule
* @author dYdX
*
* @dev Defines a function from block timestamp to epoch number.
*
* The formula used is `n = floor((t - b) / a)` where:
* - `n` is the epoch number
* - `t` is the timestamp (in seconds)
* - `b` is a non-negative offset, indicating the start of epoch zero (in seconds)
* - `a` is the length of an epoch, a.k.a. the interval (in seconds)
*
* Note that by restricting `b` to be non-negative, we limit ourselves to functions in which epoch
* zero starts at a non-negative timestamp.
*
* The recommended epoch length and blackout window are 28 and 7 days respectively; however, these
* are modifiable by the admin, within the specified bounds.
*/
abstract contract SM1EpochSchedule is
SM1Storage
{
using SafeCast for uint256;
using SafeMath for uint256;
// ============ Events ============
event EpochParametersChanged(
SM1Types.EpochParameters epochParameters
);
event BlackoutWindowChanged(
uint256 blackoutWindow
);
// ============ Initializer ============
function __SM1EpochSchedule_init(
uint256 interval,
uint256 offset,
uint256 blackoutWindow
)
internal
{
require(
block.timestamp < offset,
'SM1EpochSchedule: Epoch zero must start after initialization'
);
_setBlackoutWindow(blackoutWindow);
_setEpochParameters(interval, offset);
}
// ============ Public Functions ============
/**
* @notice Get the epoch at the current block timestamp.
*
* NOTE: Reverts if epoch zero has not started.
*
* @return The current epoch number.
*/
function getCurrentEpoch()
public
view
returns (uint256)
{
(uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp();
return offsetTimestamp.div(interval);
}
/**
* @notice Get the time remaining in the current epoch.
*
* NOTE: Reverts if epoch zero has not started.
*
* @return The number of seconds until the next epoch.
*/
function getTimeRemainingInCurrentEpoch()
public
view
returns (uint256)
{
(uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp();
uint256 timeElapsedInEpoch = offsetTimestamp.mod(interval);
return interval.sub(timeElapsedInEpoch);
}
/**
* @notice Given an epoch number, get the start of that epoch. Calculated as `t = (n * a) + b`.
*
* @return The timestamp in seconds representing the start of that epoch.
*/
function getStartOfEpoch(
uint256 epochNumber
)
public
view
returns (uint256)
{
SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_;
uint256 interval = uint256(epochParameters.interval);
uint256 offset = uint256(epochParameters.offset);
return epochNumber.mul(interval).add(offset);
}
/**
* @notice Check whether we are at or past the start of epoch zero.
*
* @return Boolean `true` if the current timestamp is at least the start of epoch zero,
* otherwise `false`.
*/
function hasEpochZeroStarted()
public
view
returns (bool)
{
SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_;
uint256 offset = uint256(epochParameters.offset);
return block.timestamp >= offset;
}
/**
* @notice Check whether we are in a blackout window, where withdrawal requests are restricted.
* Note that before epoch zero has started, there are no blackout windows.
*
* @return Boolean `true` if we are in a blackout window, otherwise `false`.
*/
function inBlackoutWindow()
public
view
returns (bool)
{
return hasEpochZeroStarted() && getTimeRemainingInCurrentEpoch() <= _BLACKOUT_WINDOW_;
}
// ============ Internal Functions ============
function _setEpochParameters(
uint256 interval,
uint256 offset
)
internal
{
SM1Types.EpochParameters memory epochParameters =
SM1Types.EpochParameters({interval: interval.toUint128(), offset: offset.toUint128()});
_EPOCH_PARAMETERS_ = epochParameters;
emit EpochParametersChanged(epochParameters);
}
function _setBlackoutWindow(
uint256 blackoutWindow
)
internal
{
_BLACKOUT_WINDOW_ = blackoutWindow;
emit BlackoutWindowChanged(blackoutWindow);
}
// ============ Private Functions ============
/**
* @dev Helper function to read params from storage and apply offset to the given timestamp.
* Recall that the formula for epoch number is `n = (t - b) / a`.
*
* NOTE: Reverts if epoch zero has not started.
*
* @return The values `a` and `(t - b)`.
*/
function _getIntervalAndOffsetTimestamp()
private
view
returns (uint256, uint256)
{
SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_;
uint256 interval = uint256(epochParameters.interval);
uint256 offset = uint256(epochParameters.offset);
require(
block.timestamp >= offset,
'SM1EpochSchedule: Epoch zero has not started'
);
uint256 offsetTimestamp = block.timestamp.sub(offset);
return (interval, offsetTimestamp);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { IERC20Detailed } from '../../../interfaces/IERC20Detailed.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1GovernancePowerDelegation } from './SM1GovernancePowerDelegation.sol';
import { SM1StakedBalances } from './SM1StakedBalances.sol';
/**
* @title SM1ERC20
* @author dYdX
*
* @dev ERC20 interface for staked tokens. Implements governance functionality for the tokens.
*
* Also allows a user with an active stake to transfer their staked tokens to another user,
* even if they would otherwise be restricted from withdrawing.
*/
abstract contract SM1ERC20 is
SM1StakedBalances,
SM1GovernancePowerDelegation,
IERC20Detailed
{
using SafeMath for uint256;
// ============ Constants ============
/// @notice EIP-712 typehash for token approval via EIP-2612 permit.
bytes32 public constant PERMIT_TYPEHASH = keccak256(
'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)'
);
// ============ External Functions ============
function name()
external
pure
override
returns (string memory)
{
return 'Staked DYDX';
}
function symbol()
external
pure
override
returns (string memory)
{
return 'stkDYDX';
}
function decimals()
external
pure
override
returns (uint8)
{
return 18;
}
/**
* @notice Get the total supply of staked balances.
*
* Note that due to the exchange rate, this is different than querying the total balance of
* underyling token staked to this contract.
*
* @return The sum of all staked balances.
*/
function totalSupply()
external
view
override
returns (uint256)
{
return getTotalActiveBalanceCurrentEpoch() + getTotalInactiveBalanceCurrentEpoch();
}
/**
* @notice Get a user's staked balance.
*
* Note that due to the exchange rate, one unit of staked balance may not be equivalent to one
* unit of the underlying token. Also note that a user's staked balance is different from a
* user's transferable balance.
*
* @param account The account to get the balance of.
*
* @return The user's staked balance.
*/
function balanceOf(
address account
)
public
view
override(SM1GovernancePowerDelegation, IERC20)
returns (uint256)
{
return getActiveBalanceCurrentEpoch(account) + getInactiveBalanceCurrentEpoch(account);
}
function transfer(
address recipient,
uint256 amount
)
external
override
nonReentrant
returns (bool)
{
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(
address owner,
address spender
)
external
view
override
returns (uint256)
{
return _ALLOWANCES_[owner][spender];
}
function approve(
address spender,
uint256 amount
)
external
override
returns (bool)
{
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
)
external
override
nonReentrant
returns (bool)
{
_transfer(sender, recipient, amount);
_approve(
sender,
msg.sender,
_ALLOWANCES_[sender][msg.sender].sub(amount, 'SM1ERC20: transfer amount exceeds allowance')
);
return true;
}
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
_approve(msg.sender, spender, _ALLOWANCES_[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
_approve(
msg.sender,
spender,
_ALLOWANCES_[msg.sender][spender].sub(
subtractedValue,
'SM1ERC20: Decreased allowance below zero'
)
);
return true;
}
/**
* @notice Implements the permit function as specified in EIP-2612.
*
* @param owner Address of the token owner.
* @param spender Address of the spender.
* @param value Amount of allowance.
* @param deadline Expiration timestamp for the signature.
* @param v Signature param.
* @param r Signature param.
* @param s Signature param.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
require(
owner != address(0),
'SM1ERC20: INVALID_OWNER'
);
require(
block.timestamp <= deadline,
'SM1ERC20: INVALID_EXPIRATION'
);
uint256 currentValidNonce = _NONCES_[owner];
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
_DOMAIN_SEPARATOR_,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline))
)
);
require(
owner == ecrecover(digest, v, r, s),
'SM1ERC20: INVALID_SIGNATURE'
);
_NONCES_[owner] = currentValidNonce.add(1);
_approve(owner, spender, value);
}
// ============ Internal Functions ============
function _transfer(
address sender,
address recipient,
uint256 amount
)
internal
{
require(
sender != address(0),
'SM1ERC20: Transfer from address(0)'
);
require(
recipient != address(0),
'SM1ERC20: Transfer to address(0)'
);
require(
getTransferableBalance(sender) >= amount,
'SM1ERC20: Transfer exceeds next epoch active balance'
);
// Update staked balances and delegate snapshots.
_transferCurrentAndNextActiveBalance(sender, recipient, amount);
_moveDelegatesForTransfer(sender, recipient, amount);
emit Transfer(sender, recipient, amount);
}
function _approve(
address owner,
address spender,
uint256 amount
)
internal
{
require(
owner != address(0),
'SM1ERC20: Approve from address(0)'
);
require(
spender != address(0),
'SM1ERC20: Approve to address(0)'
);
_ALLOWANCES_[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
import { IERC20 } from './IERC20.sol';
/**
* @dev Interface for ERC20 including metadata
**/
interface IERC20Detailed is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import {
IGovernancePowerDelegationERC20
} from '../../../interfaces/IGovernancePowerDelegationERC20.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1ExchangeRate } from './SM1ExchangeRate.sol';
import { SM1Storage } from './SM1Storage.sol';
/**
* @title SM1GovernancePowerDelegation
* @author dYdX
*
* @dev Provides support for two types of governance powers which are separately delegatable.
* Provides functions for delegation and for querying a user's power at a certain block number.
*
* Internally, makes use of staked balances denoted in staked units, but returns underlying token
* units from the getPowerAtBlock() and getPowerCurrent() functions.
*
* This is based on, and is designed to match, Aave's implementation, which is used in their
* governance token and staked token contracts.
*/
abstract contract SM1GovernancePowerDelegation is
SM1ExchangeRate,
IGovernancePowerDelegationERC20
{
using SafeMath for uint256;
// ============ Constants ============
/// @notice EIP-712 typehash for delegation by signature of a specific governance power type.
bytes32 public constant DELEGATE_BY_TYPE_TYPEHASH = keccak256(
'DelegateByType(address delegatee,uint256 type,uint256 nonce,uint256 expiry)'
);
/// @notice EIP-712 typehash for delegation by signature of all governance powers.
bytes32 public constant DELEGATE_TYPEHASH = keccak256(
'Delegate(address delegatee,uint256 nonce,uint256 expiry)'
);
// ============ External Functions ============
/**
* @notice Delegates a specific governance power of the sender to a delegatee.
*
* @param delegatee The address to delegate power to.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
*/
function delegateByType(
address delegatee,
DelegationType delegationType
)
external
override
{
_delegateByType(msg.sender, delegatee, delegationType);
}
/**
* @notice Delegates all governance powers of the sender to a delegatee.
*
* @param delegatee The address to delegate power to.
*/
function delegate(
address delegatee
)
external
override
{
_delegateByType(msg.sender, delegatee, DelegationType.VOTING_POWER);
_delegateByType(msg.sender, delegatee, DelegationType.PROPOSITION_POWER);
}
/**
* @dev Delegates specific governance power from signer to `delegatee` using an EIP-712 signature.
*
* @param delegatee The address to delegate votes to.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
* @param nonce The signer's nonce for EIP-712 signatures on this contract.
* @param expiry Expiration timestamp for the signature.
* @param v Signature param.
* @param r Signature param.
* @param s Signature param.
*/
function delegateByTypeBySig(
address delegatee,
DelegationType delegationType,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 structHash = keccak256(
abi.encode(DELEGATE_BY_TYPE_TYPEHASH, delegatee, uint256(delegationType), nonce, expiry)
);
bytes32 digest = keccak256(abi.encodePacked('\x19\x01', _DOMAIN_SEPARATOR_, structHash));
address signer = ecrecover(digest, v, r, s);
require(
signer != address(0),
'SM1GovernancePowerDelegation: INVALID_SIGNATURE'
);
require(
nonce == _NONCES_[signer]++,
'SM1GovernancePowerDelegation: INVALID_NONCE'
);
require(
block.timestamp <= expiry,
'SM1GovernancePowerDelegation: INVALID_EXPIRATION'
);
_delegateByType(signer, delegatee, delegationType);
}
/**
* @dev Delegates both governance powers from signer to `delegatee` using an EIP-712 signature.
*
* @param delegatee The address to delegate votes to.
* @param nonce The signer's nonce for EIP-712 signatures on this contract.
* @param expiry Expiration timestamp for the signature.
* @param v Signature param.
* @param r Signature param.
* @param s Signature param.
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 structHash = keccak256(abi.encode(DELEGATE_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked('\x19\x01', _DOMAIN_SEPARATOR_, structHash));
address signer = ecrecover(digest, v, r, s);
require(
signer != address(0),
'SM1GovernancePowerDelegation: INVALID_SIGNATURE'
);
require(
nonce == _NONCES_[signer]++,
'SM1GovernancePowerDelegation: INVALID_NONCE'
);
require(
block.timestamp <= expiry,
'SM1GovernancePowerDelegation: INVALID_EXPIRATION'
);
_delegateByType(signer, delegatee, DelegationType.VOTING_POWER);
_delegateByType(signer, delegatee, DelegationType.PROPOSITION_POWER);
}
/**
* @notice Returns the delegatee of a user.
*
* @param delegator The address of the delegator.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
*/
function getDelegateeByType(
address delegator,
DelegationType delegationType
)
external
override
view
returns (address)
{
(, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType);
return _getDelegatee(delegator, delegates);
}
/**
* @notice Returns the current power of a user. The current power is the power delegated
* at the time of the last snapshot.
*
* @param user The user whose power to query.
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*/
function getPowerCurrent(
address user,
DelegationType delegationType
)
external
override
view
returns (uint256)
{
return getPowerAtBlock(user, block.number, delegationType);
}
/**
* @notice Get the next valid nonce for EIP-712 signatures.
*
* This nonce should be used when signing for any of the following functions:
* - permit()
* - delegateByTypeBySig()
* - delegateBySig()
*/
function nonces(
address owner
)
external
view
returns (uint256)
{
return _NONCES_[owner];
}
// ============ Public Functions ============
function balanceOf(
address account
)
public
view
virtual
returns (uint256);
/**
* @notice Returns the power of a user at a certain block, denominated in underlying token units.
*
* @param user The user whose power to query.
* @param blockNumber The block number at which to get the user's power.
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*
* @return The user's governance power of the specified type, in underlying token units.
*/
function getPowerAtBlock(
address user,
uint256 blockNumber,
DelegationType delegationType
)
public
override
view
returns (uint256)
{
(
mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage snapshots,
mapping(address => uint256) storage snapshotCounts,
// unused: delegates
) = _getDelegationDataByType(delegationType);
uint256 stakeAmount = _findValueAtBlock(
snapshots[user],
snapshotCounts[user],
blockNumber,
0
);
uint256 exchangeRate = _findValueAtBlock(
_EXCHANGE_RATE_SNAPSHOTS_,
_EXCHANGE_RATE_SNAPSHOT_COUNT_,
blockNumber,
EXCHANGE_RATE_BASE
);
return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, exchangeRate);
}
// ============ Internal Functions ============
/**
* @dev Delegates one specific power to a delegatee.
*
* @param delegator The user whose power to delegate.
* @param delegatee The address to delegate power to.
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*/
function _delegateByType(
address delegator,
address delegatee,
DelegationType delegationType
)
internal
{
require(
delegatee != address(0),
'SM1GovernancePowerDelegation: INVALID_DELEGATEE'
);
(, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType);
uint256 delegatorBalance = balanceOf(delegator);
address previousDelegatee = _getDelegatee(delegator, delegates);
delegates[delegator] = delegatee;
_moveDelegatesByType(previousDelegatee, delegatee, delegatorBalance, delegationType);
emit DelegateChanged(delegator, delegatee, delegationType);
}
/**
* @dev Update delegate snapshots whenever staked tokens are transfered, minted, or burned.
*
* @param from The sender.
* @param to The recipient.
* @param stakedAmount The amount being transfered, denominated in staked units.
*/
function _moveDelegatesForTransfer(
address from,
address to,
uint256 stakedAmount
)
internal
{
address votingPowerFromDelegatee = _getDelegatee(from, _VOTING_DELEGATES_);
address votingPowerToDelegatee = _getDelegatee(to, _VOTING_DELEGATES_);
_moveDelegatesByType(
votingPowerFromDelegatee,
votingPowerToDelegatee,
stakedAmount,
DelegationType.VOTING_POWER
);
address propositionPowerFromDelegatee = _getDelegatee(from, _PROPOSITION_DELEGATES_);
address propositionPowerToDelegatee = _getDelegatee(to, _PROPOSITION_DELEGATES_);
_moveDelegatesByType(
propositionPowerFromDelegatee,
propositionPowerToDelegatee,
stakedAmount,
DelegationType.PROPOSITION_POWER
);
}
/**
* @dev Moves power from one user to another.
*
* @param from The user from which delegated power is moved.
* @param to The user that will receive the delegated power.
* @param amount The amount of power to be moved.
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*/
function _moveDelegatesByType(
address from,
address to,
uint256 amount,
DelegationType delegationType
)
internal
{
if (from == to) {
return;
}
(
mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage snapshots,
mapping(address => uint256) storage snapshotCounts,
// unused: delegates
) = _getDelegationDataByType(delegationType);
if (from != address(0)) {
mapping(uint256 => SM1Types.Snapshot) storage fromSnapshots = snapshots[from];
uint256 fromSnapshotCount = snapshotCounts[from];
uint256 previousBalance = 0;
if (fromSnapshotCount != 0) {
previousBalance = fromSnapshots[fromSnapshotCount - 1].value;
}
uint256 newBalance = previousBalance.sub(amount);
snapshotCounts[from] = _writeSnapshot(
fromSnapshots,
fromSnapshotCount,
newBalance
);
emit DelegatedPowerChanged(from, newBalance, delegationType);
}
if (to != address(0)) {
mapping(uint256 => SM1Types.Snapshot) storage toSnapshots = snapshots[to];
uint256 toSnapshotCount = snapshotCounts[to];
uint256 previousBalance = 0;
if (toSnapshotCount != 0) {
previousBalance = toSnapshots[toSnapshotCount - 1].value;
}
uint256 newBalance = previousBalance.add(amount);
snapshotCounts[to] = _writeSnapshot(
toSnapshots,
toSnapshotCount,
newBalance
);
emit DelegatedPowerChanged(to, newBalance, delegationType);
}
}
/**
* @dev Returns delegation data (snapshot, snapshotCount, delegates) by delegation type.
*
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*
* @return The mapping of each user to a mapping of snapshots.
* @return The mapping of each user to the total number of snapshots for that user.
* @return The mapping of each user to the user's delegate.
*/
function _getDelegationDataByType(
DelegationType delegationType
)
internal
view
returns (
mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage,
mapping(address => uint256) storage,
mapping(address => address) storage
)
{
if (delegationType == DelegationType.VOTING_POWER) {
return (
_VOTING_SNAPSHOTS_,
_VOTING_SNAPSHOT_COUNTS_,
_VOTING_DELEGATES_
);
} else {
return (
_PROPOSITION_SNAPSHOTS_,
_PROPOSITION_SNAPSHOT_COUNTS_,
_PROPOSITION_DELEGATES_
);
}
}
/**
* @dev Returns the delegatee of a user. If a user never performed any delegation, their
* delegated address will be 0x0, in which case we return the user's own address.
*
* @param delegator The address of the user for which return the delegatee.
* @param delegates The mapping of delegates for a particular type of delegation.
*/
function _getDelegatee(
address delegator,
mapping(address => address) storage delegates
)
internal
view
returns (address)
{
address previousDelegatee = delegates[delegator];
if (previousDelegatee == address(0)) {
return delegator;
}
return previousDelegatee;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
interface IGovernancePowerDelegationERC20 {
enum DelegationType {
VOTING_POWER,
PROPOSITION_POWER
}
/**
* @dev Emitted when a user delegates governance power to another user.
*
* @param delegator The delegator.
* @param delegatee The delegatee.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
*/
event DelegateChanged(
address indexed delegator,
address indexed delegatee,
DelegationType delegationType
);
/**
* @dev Emitted when an action changes the delegated power of a user.
*
* @param user The user whose delegated power has changed.
* @param amount The new amount of delegated power for the user.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
*/
event DelegatedPowerChanged(address indexed user, uint256 amount, DelegationType delegationType);
/**
* @dev Delegates a specific governance power to a delegatee.
*
* @param delegatee The address to delegate power to.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
*/
function delegateByType(address delegatee, DelegationType delegationType) external virtual;
/**
* @dev Delegates all governance powers to a delegatee.
*
* @param delegatee The user to which the power will be delegated.
*/
function delegate(address delegatee) external virtual;
/**
* @dev Returns the delegatee of an user.
*
* @param delegator The address of the delegator.
* @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER).
*/
function getDelegateeByType(address delegator, DelegationType delegationType)
external
view
virtual
returns (address);
/**
* @dev Returns the current delegated power of a user. The current power is the power delegated
* at the time of the last snapshot.
*
* @param user The user whose power to query.
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*/
function getPowerCurrent(address user, DelegationType delegationType)
external
view
virtual
returns (uint256);
/**
* @dev Returns the delegated power of a user at a certain block.
*
* @param user The user whose power to query.
* @param blockNumber The block number at which to get the user's power.
* @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER).
*/
function getPowerAtBlock(
address user,
uint256 blockNumber,
DelegationType delegationType
)
external
view
virtual
returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { SM1Snapshots } from './SM1Snapshots.sol';
import { SM1Storage } from './SM1Storage.sol';
/**
* @title SM1ExchangeRate
* @author dYdX
*
* @dev Performs math using the exchange rate, which converts between underlying units of the token
* that was staked (e.g. STAKED_TOKEN.balanceOf(account)), and staked units, used by this contract
* for all staked balances (e.g. this.balanceOf(account)).
*
* OVERVIEW:
*
* The exchange rate is stored as a multiple of EXCHANGE_RATE_BASE, and represents the number of
* staked balance units that each unit of underlying token is worth. Before any slashes have
* occurred, the exchange rate is equal to one. The exchange rate can increase with each slash,
* indicating that staked balances are becoming less and less valuable, per unit, relative to the
* underlying token.
*
* AVOIDING OVERFLOW AND UNDERFLOW:
*
* Staked balances are represented internally as uint240, so the result of an operation returning
* a staked balances must return a value less than 2^240. Intermediate values in calcuations are
* represented as uint256, so all operations within a calculation must return values under 2^256.
*
* In the functions below operating on the exchange rate, we are strategic in our choice of the
* order of multiplication and division operations, in order to avoid both overflow and underflow.
*
* We use the following assumptions and principles to implement this module:
* - (ASSUMPTION) An amount denoted in underlying token units is never greater than 10^28.
* - If the exchange rate is greater than 10^46, then we may perform division on the exchange
* rate before performing multiplication, provided that the denominator is not greater
* than 10^28 (to ensure a result with at least 18 decimals of precision). Specifically,
* we use EXCHANGE_RATE_MAY_OVERFLOW as the cutoff, which is a number greater than 10^46.
* - Since staked balances are stored as uint240, we cap the exchange rate to ensure that a
* staked balance can never overflow (using the assumption above).
*/
abstract contract SM1ExchangeRate is
SM1Snapshots,
SM1Storage
{
using SafeMath for uint256;
// ============ Constants ============
/// @notice The assumed upper bound on the total supply of the staked token.
uint256 public constant MAX_UNDERLYING_BALANCE = 1e28;
/// @notice Base unit used to represent the exchange rate, for additional precision.
uint256 public constant EXCHANGE_RATE_BASE = 1e18;
/// @notice Cutoff where an exchange rate may overflow after multiplying by an underlying balance.
/// @dev Approximately 1.2e49
uint256 public constant EXCHANGE_RATE_MAY_OVERFLOW = (2 ** 256 - 1) / MAX_UNDERLYING_BALANCE;
/// @notice Cutoff where a stake amount may overflow after multiplying by EXCHANGE_RATE_BASE.
/// @dev Approximately 1.2e59
uint256 public constant STAKE_AMOUNT_MAY_OVERFLOW = (2 ** 256 - 1) / EXCHANGE_RATE_BASE;
/// @notice Max exchange rate.
/// @dev Approximately 1.8e62
uint256 public constant MAX_EXCHANGE_RATE = (
((2 ** 240 - 1) / MAX_UNDERLYING_BALANCE) * EXCHANGE_RATE_BASE
);
// ============ Initializer ============
function __SM1ExchangeRate_init()
internal
{
_EXCHANGE_RATE_ = EXCHANGE_RATE_BASE;
}
function stakeAmountFromUnderlyingAmount(
uint256 underlyingAmount
)
internal
view
returns (uint256)
{
uint256 exchangeRate = _EXCHANGE_RATE_;
if (exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) {
uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE);
return underlyingAmount.mul(exchangeRateUnbased);
} else {
return underlyingAmount.mul(exchangeRate).div(EXCHANGE_RATE_BASE);
}
}
function underlyingAmountFromStakeAmount(
uint256 stakeAmount
)
internal
view
returns (uint256)
{
return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, _EXCHANGE_RATE_);
}
function underlyingAmountFromStakeAmountWithExchangeRate(
uint256 stakeAmount,
uint256 exchangeRate
)
internal
pure
returns (uint256)
{
if (stakeAmount > STAKE_AMOUNT_MAY_OVERFLOW) {
// Note that this case implies that exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW.
uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE);
return stakeAmount.div(exchangeRateUnbased);
} else {
return stakeAmount.mul(EXCHANGE_RATE_BASE).div(exchangeRate);
}
}
function updateExchangeRate(
uint256 numerator,
uint256 denominator
)
internal
returns (uint256)
{
uint256 oldExchangeRate = _EXCHANGE_RATE_;
// Avoid overflow.
// Note that the numerator and denominator are both denominated in underlying token units.
uint256 newExchangeRate;
if (oldExchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) {
newExchangeRate = oldExchangeRate.div(denominator).mul(numerator);
} else {
newExchangeRate = oldExchangeRate.mul(numerator).div(denominator);
}
require(
newExchangeRate <= MAX_EXCHANGE_RATE,
'SM1ExchangeRate: Max exchange rate exceeded'
);
_EXCHANGE_RATE_SNAPSHOT_COUNT_ = _writeSnapshot(
_EXCHANGE_RATE_SNAPSHOTS_,
_EXCHANGE_RATE_SNAPSHOT_COUNT_,
newExchangeRate
);
_EXCHANGE_RATE_ = newExchangeRate;
return newExchangeRate;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1Storage } from './SM1Storage.sol';
/**
* @title SM1Snapshots
* @author dYdX
*
* @dev Handles storage and retrieval of historical values by block number.
*
* Note that the snapshot stored at a given block number represents the value as of the end of
* that block.
*/
abstract contract SM1Snapshots {
/**
* @dev Writes a snapshot of a value at the current block.
*
* @param snapshots Storage mapping from snapshot index to snapshot struct.
* @param snapshotCount The total number of snapshots in the provided mapping.
* @param newValue The new value to snapshot at the current block.
*
* @return The new snapshot count.
*/
function _writeSnapshot(
mapping(uint256 => SM1Types.Snapshot) storage snapshots,
uint256 snapshotCount,
uint256 newValue
)
internal
returns (uint256)
{
uint256 currentBlock = block.number;
if (
snapshotCount != 0 &&
snapshots[snapshotCount - 1].blockNumber == currentBlock
) {
// If there was a previous snapshot for this block, overwrite it.
snapshots[snapshotCount - 1].value = newValue;
return snapshotCount;
} else {
snapshots[snapshotCount] = SM1Types.Snapshot(currentBlock, newValue);
return snapshotCount + 1;
}
}
/**
* @dev Search for the snapshot value at a given block. Uses binary search.
*
* Reverts if `blockNumber` is greater than the current block number.
*
* @param snapshots Storage mapping from snapshot index to snapshot struct.
* @param snapshotCount The total number of snapshots in the provided mapping.
* @param blockNumber The block number to search for.
* @param initialValue The value to return if `blockNumber` is before the earliest snapshot.
*
* @return The snapshot value at the specified block number.
*/
function _findValueAtBlock(
mapping(uint256 => SM1Types.Snapshot) storage snapshots,
uint256 snapshotCount,
uint256 blockNumber,
uint256 initialValue
)
internal
view
returns (uint256)
{
require(
blockNumber <= block.number,
'SM1Snapshots: INVALID_BLOCK_NUMBER'
);
if (snapshotCount == 0) {
return initialValue;
}
// Check earliest snapshot.
if (blockNumber < snapshots[0].blockNumber) {
return initialValue;
}
// Check latest snapshot.
if (blockNumber >= snapshots[snapshotCount - 1].blockNumber) {
return snapshots[snapshotCount - 1].value;
}
uint256 lower = 0;
uint256 upper = snapshotCount - 1;
while (upper > lower) {
uint256 center = upper - (upper - lower) / 2; // Ceil, avoiding overflow.
SM1Types.Snapshot memory snapshot = snapshots[center];
if (snapshot.blockNumber == blockNumber) {
return snapshot.value;
} else if (snapshot.blockNumber < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return snapshots[lower].value;
}
}
| ============ Events ============ ============ Initializer ============ | {
using SafeCast for uint256;
using SafeMath for uint256;
event EpochParametersChanged(
SM1Types.EpochParameters epochParameters
);
event BlackoutWindowChanged(
uint256 blackoutWindow
);
function __SM1EpochSchedule_init(
uint256 interval,
uint256 offset,
uint256 blackoutWindow
)
internal
pragma solidity 0.7.5;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { SafeCast } from '../lib/SafeCast.sol';
import { SM1Types } from '../lib/SM1Types.sol';
import { SM1Storage } from './SM1Storage.sol';
abstract contract SM1EpochSchedule is
{
require(
block.timestamp < offset,
'SM1EpochSchedule: Epoch zero must start after initialization'
);
_setBlackoutWindow(blackoutWindow);
_setEpochParameters(interval, offset);
}
function getCurrentEpoch()
public
view
returns (uint256)
{
(uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp();
return offsetTimestamp.div(interval);
}
function getTimeRemainingInCurrentEpoch()
public
view
returns (uint256)
{
(uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp();
uint256 timeElapsedInEpoch = offsetTimestamp.mod(interval);
return interval.sub(timeElapsedInEpoch);
}
function getStartOfEpoch(
uint256 epochNumber
)
public
view
returns (uint256)
{
SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_;
uint256 interval = uint256(epochParameters.interval);
uint256 offset = uint256(epochParameters.offset);
return epochNumber.mul(interval).add(offset);
}
function hasEpochZeroStarted()
public
view
returns (bool)
{
SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_;
uint256 offset = uint256(epochParameters.offset);
return block.timestamp >= offset;
}
function inBlackoutWindow()
public
view
returns (bool)
{
return hasEpochZeroStarted() && getTimeRemainingInCurrentEpoch() <= _BLACKOUT_WINDOW_;
}
function _setEpochParameters(
uint256 interval,
uint256 offset
)
internal
{
SM1Types.EpochParameters memory epochParameters =
_EPOCH_PARAMETERS_ = epochParameters;
emit EpochParametersChanged(epochParameters);
}
SM1Types.EpochParameters({interval: interval.toUint128(), offset: offset.toUint128()});
function _setBlackoutWindow(
uint256 blackoutWindow
)
internal
{
_BLACKOUT_WINDOW_ = blackoutWindow;
emit BlackoutWindowChanged(blackoutWindow);
}
function _getIntervalAndOffsetTimestamp()
private
view
returns (uint256, uint256)
{
SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_;
uint256 interval = uint256(epochParameters.interval);
uint256 offset = uint256(epochParameters.offset);
require(
block.timestamp >= offset,
'SM1EpochSchedule: Epoch zero has not started'
);
uint256 offsetTimestamp = block.timestamp.sub(offset);
return (interval, offsetTimestamp);
}
}
| 204,016 | [
1,
14468,
9043,
422,
1432,
631,
422,
1432,
631,
4378,
3926,
422,
1432,
631,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
95,
203,
225,
1450,
14060,
9735,
364,
2254,
5034,
31,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
203,
225,
871,
512,
6127,
2402,
5033,
12,
203,
565,
12014,
21,
2016,
18,
14638,
2402,
7632,
2402,
203,
225,
11272,
203,
203,
225,
871,
22467,
659,
3829,
5033,
12,
203,
565,
2254,
5034,
7721,
659,
3829,
203,
225,
11272,
203,
203,
203,
225,
445,
1001,
7303,
21,
14638,
6061,
67,
2738,
12,
203,
565,
2254,
5034,
3673,
16,
203,
565,
2254,
5034,
1384,
16,
203,
565,
2254,
5034,
7721,
659,
3829,
203,
225,
262,
203,
565,
2713,
203,
683,
9454,
18035,
560,
374,
18,
27,
18,
25,
31,
203,
5666,
288,
14060,
10477,
289,
628,
296,
16644,
6216,
11037,
19,
3190,
17,
94,
881,
84,
292,
267,
19,
9890,
10477,
18,
18281,
13506,
203,
5666,
288,
14060,
9735,
289,
628,
25226,
2941,
19,
9890,
9735,
18,
18281,
13506,
203,
5666,
288,
12014,
21,
2016,
289,
628,
25226,
2941,
19,
7303,
21,
2016,
18,
18281,
13506,
203,
5666,
288,
12014,
21,
3245,
289,
628,
12871,
7303,
21,
3245,
18,
18281,
13506,
203,
17801,
6835,
12014,
21,
14638,
6061,
353,
203,
225,
288,
203,
565,
2583,
12,
203,
1377,
1203,
18,
5508,
411,
1384,
16,
203,
1377,
296,
7303,
21,
14638,
6061,
30,
512,
6127,
3634,
1297,
787,
1839,
10313,
11,
203,
565,
11272,
203,
565,
389,
542,
13155,
659,
3829,
12,
11223,
659,
3829,
1769,
203,
565,
389,
542,
14638,
2402,
12,
6624,
16,
1384,
1769,
203,
225,
289,
203,
203,
203,
225,
2
]
|
./full_match/80001/0xf933e54D24eBdF781f6C21Ed6C48185678D155ef/sources/contracts/SkyGenerator.sol | * Gets Layer, usually of compiled symbols/ | function getLayer(Params calldata params ) public view returns (string memory artwork){
string memory symbols = '';
for(uint i=0; i<params.intensity; i++){
symbols = string.concat(symbols, ISvgUtilsGenerator(svgUtilsAddress).getSymbol(
ICloudArtwork(nftArtworkAddress).getArtwork(params.ids[i]),
'pa-1',
string.concat('s',Strings.toString(i))
)
);
}
'</defs><g class="pl">',
'<use class="useme" href="#s0" y="-200" />',
'<use class="useme" href="#s1" y="-100" />',
'<use class="useme" href="#s2" y="0" />',
'<use class="useme" href="#s3" y="100" />',
'<use class="useme" href="#s4" y="200" />',
}
| 868,787 | [
1,
3002,
12112,
16,
11234,
434,
7743,
7963,
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,
25763,
12,
1370,
745,
892,
859,
225,
262,
1071,
1476,
1135,
261,
1080,
3778,
3688,
1252,
15329,
203,
1377,
533,
3778,
7963,
273,
26028,
203,
4202,
364,
12,
11890,
277,
33,
20,
31,
277,
32,
2010,
18,
474,
6318,
31,
277,
27245,
95,
203,
6647,
203,
3639,
7963,
273,
533,
18,
16426,
12,
15536,
16,
4437,
20105,
1989,
3908,
12,
11451,
1989,
1887,
2934,
588,
5335,
12,
203,
1850,
467,
6230,
4411,
1252,
12,
82,
1222,
4411,
1252,
1887,
2934,
588,
4411,
1252,
12,
2010,
18,
2232,
63,
77,
65,
3631,
21281,
1850,
296,
8774,
17,
21,
2187,
203,
1850,
533,
18,
16426,
2668,
87,
2187,
7957,
18,
10492,
12,
77,
3719,
203,
1850,
262,
203,
3639,
11272,
203,
1377,
289,
203,
203,
4202,
203,
4202,
203,
1377,
4357,
12537,
4438,
75,
667,
1546,
412,
7918,
16,
7010,
1377,
2368,
1202,
225,
667,
1546,
1202,
3501,
6,
3897,
1546,
7,
87,
20,
6,
225,
677,
1546,
17,
6976,
6,
13452,
16,
203,
1377,
2368,
1202,
225,
667,
1546,
1202,
3501,
6,
3897,
1546,
7,
87,
21,
6,
225,
677,
1546,
17,
6625,
6,
13452,
16,
203,
1377,
2368,
1202,
225,
667,
1546,
1202,
3501,
6,
3897,
1546,
7,
87,
22,
6,
225,
677,
1546,
20,
6,
13452,
16,
203,
1377,
2368,
1202,
225,
667,
1546,
1202,
3501,
6,
3897,
1546,
7,
87,
23,
6,
225,
677,
1546,
6625,
6,
13452,
16,
203,
1377,
2368,
1202,
225,
667,
1546,
1202,
3501,
6,
3897,
1546,
7,
87,
24,
6,
225,
677,
1546,
6976,
6,
2
]
|
./full_match/44787/0xe5de984Cd472d40E8970B8fc119008f4E175adE6/sources/contracts/StarNFT.sol | Stake Star NFT to MasterChef | function enterStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
require(starNFT.ownerOf(_tokenId) == _msgSender(), "error NFT user");
require(userNFTs[_msgSender()].length > 0, "star token user");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
if (_nftAmountGain > 0) {
uint256 pending = _nftAmountGain.mul(pool.accStarPerShare).div(1e12).sub(user.nftRewardDebt);
if(pending > 0) {
if (user.nftLastDeposit > block.timestamp.sub(604800)) {
pending = pending.mul(90).div(100);
starToken.safeTransfer(bonusAddr, pending.mul(10).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.amount);
}
}
if (_tokenId > 0) {
starNFT.transferFrom(_msgSender(), address(this), _tokenId);
userNFTs[_msgSender()].push(_tokenId);
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
uint256 _extraAmount = _amount.add(_amount.mul(_selfGain.add(_parentGain)).div(100));
pool.extraAmount = pool.extraAmount.add(_extraAmount);
user.amount = user.amount.add(_amount);
user.nftAmount = user.nftAmount.add(_amount);
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
_nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
}
emit Deposit(_msgSender(), 0, _tokenId, isNodeUser[_msgSender()]);
}
| 13,263,196 | [
1,
510,
911,
934,
297,
423,
4464,
358,
13453,
39,
580,
74,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
6103,
510,
6159,
50,
4464,
12,
11890,
5034,
389,
2316,
548,
13,
1071,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
20,
15533,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
20,
6362,
67,
3576,
12021,
1435,
15533,
203,
202,
202,
6528,
12,
10983,
50,
4464,
18,
8443,
951,
24899,
2316,
548,
13,
422,
389,
3576,
12021,
9334,
315,
1636,
423,
4464,
729,
8863,
203,
3639,
2583,
12,
1355,
50,
4464,
87,
63,
67,
3576,
12021,
1435,
8009,
2469,
405,
374,
16,
315,
10983,
1147,
729,
8863,
203,
3639,
1089,
2864,
12,
20,
1769,
203,
203,
3639,
261,
11890,
5034,
389,
2890,
43,
530,
16,
2254,
5034,
389,
2938,
43,
530,
13,
273,
10443,
907,
18,
2159,
43,
530,
5621,
203,
3639,
2254,
5034,
389,
8949,
43,
530,
273,
729,
18,
8949,
18,
1289,
12,
1355,
18,
8949,
18,
16411,
24899,
2890,
43,
530,
2934,
2892,
12,
6625,
10019,
203,
3639,
2254,
5034,
389,
82,
1222,
6275,
43,
530,
273,
729,
18,
82,
1222,
6275,
18,
1289,
12,
1355,
18,
82,
1222,
6275,
18,
16411,
24899,
2890,
43,
530,
2934,
2892,
12,
6625,
10019,
203,
203,
3639,
309,
261,
67,
82,
1222,
6275,
43,
530,
405,
374,
13,
288,
203,
5411,
2254,
5034,
4634,
273,
389,
82,
1222,
6275,
43,
530,
18,
16411,
12,
6011,
18,
8981,
18379,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
2934,
1717,
12,
1355,
18,
82,
1222,
17631,
1060,
758,
23602,
1769,
203,
5411,
309,
12,
9561,
405,
374,
13,
288,
203,
7734,
2
]
|
//Address: 0x04f062809b244e37e7fdc21d9409469c989c2342
//Contract name: Joyso
//Balance: 230.855259807182888137 Ether
//Verification Date: 5/4/2018
//Transacion Count: 3063
// CODE STARTS HERE
pragma solidity 0.4.19;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
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;
}
}
/**
* @title Migratable
* @dev an interface for joyso to migrate to the new version
*/
contract Migratable {
function migrate(address user, uint256 amount, address tokenAddr) external payable returns (bool);
}
/**
* @title JoysoDataDecoder
* @author Will, Emn178
* @notice decode the joyso compressed data
*/
contract JoysoDataDecoder {
function decodeOrderUserId(uint256 data) internal pure returns (uint256) {
return data & 0x00000000000000000000000000000000000000000000000000000000ffffffff;
}
function retrieveV(uint256 data) internal pure returns (uint256) {
// [24..24] v 0:27 1:28
return data & 0x000000000000000000000000f000000000000000000000000000000000000000 == 0 ? 27 : 28;
}
}
/**
* @title Joyso
* @notice joyso main contract
* @author Will, Emn178
*/
contract Joyso is Ownable, JoysoDataDecoder {
using SafeMath for uint256;
uint256 private constant USER_MASK = 0x00000000000000000000000000000000000000000000000000000000ffffffff;
uint256 private constant PAYMENT_METHOD_MASK = 0x00000000000000000000000f0000000000000000000000000000000000000000;
uint256 private constant WITHDRAW_TOKEN_MASK = 0x0000000000000000000000000000000000000000000000000000ffff00000000;
uint256 private constant V_MASK = 0x000000000000000000000000f000000000000000000000000000000000000000;
uint256 private constant TOKEN_SELL_MASK = 0x000000000000000000000000000000000000000000000000ffff000000000000;
uint256 private constant TOKEN_BUY_MASK = 0x0000000000000000000000000000000000000000000000000000ffff00000000;
uint256 private constant SIGN_MASK = 0xffffffffffffffffffffffff0000000000000000000000000000000000000000;
uint256 private constant MATCH_SIGN_MASK = 0xfffffffffffffffffffffff00000000000000000000000000000000000000000;
uint256 private constant TOKEN_JOY_PRICE_MASK = 0x0000000000000000000000000fffffffffffffffffffffff0000000000000000;
uint256 private constant JOY_PRICE_MASK = 0x0000000000000000fffffff00000000000000000000000000000000000000000;
uint256 private constant IS_BUY_MASK = 0x00000000000000000000000f0000000000000000000000000000000000000000;
uint256 private constant TAKER_FEE_MASK = 0x00000000ffff0000000000000000000000000000000000000000000000000000;
uint256 private constant MAKER_FEE_MASK = 0x000000000000ffff000000000000000000000000000000000000000000000000;
uint256 private constant PAY_BY_TOKEN = 0x0000000000000000000000020000000000000000000000000000000000000000;
uint256 private constant PAY_BY_JOY = 0x0000000000000000000000010000000000000000000000000000000000000000;
uint256 private constant ORDER_ISBUY = 0x0000000000000000000000010000000000000000000000000000000000000000;
mapping (address => mapping (address => uint256)) private balances;
mapping (address => uint256) public userLock;
mapping (address => uint256) public userNonce;
mapping (bytes32 => uint256) public orderFills;
mapping (bytes32 => bool) public usedHash;
mapping (address => bool) public isAdmin;
mapping (uint256 => address) public tokenId2Address;
mapping (uint256 => address) public userId2Address;
mapping (address => uint256) public userAddress2Id;
mapping (address => uint256) public tokenAddress2Id;
address public joysoWallet;
address public joyToken;
uint256 public lockPeriod = 30 days;
uint256 public userCount;
bool public tradeEventEnabled = true;
modifier onlyAdmin {
require(msg.sender == owner || isAdmin[msg.sender]);
_;
}
//events
event Deposit(address token, address user, uint256 amount, uint256 balance);
event Withdraw(address token, address user, uint256 amount, uint256 balance);
event NewUser(address user, uint256 id);
event Lock(address user, uint256 timeLock);
// for debug
event TradeSuccess(address user, uint256 baseAmount, uint256 tokenAmount, bool isBuy, uint256 fee);
function Joyso(address _joysoWallet, address _joyToken) public {
joysoWallet = _joysoWallet;
addUser(_joysoWallet);
joyToken = _joyToken;
tokenAddress2Id[joyToken] = 1;
tokenAddress2Id[0] = 0; // ether address is Id 0
tokenId2Address[0] = 0;
tokenId2Address[1] = joyToken;
}
/**
* @notice deposit token into the contract
* @notice Be sure to Approve the contract to move your erc20 token
* @param token The address of deposited token
* @param amount The amount of token to deposit
*/
function depositToken(address token, uint256 amount) external {
require(amount > 0);
require(tokenAddress2Id[token] != 0);
addUser(msg.sender);
require(ERC20(token).transferFrom(msg.sender, this, amount));
balances[token][msg.sender] = balances[token][msg.sender].add(amount);
Deposit(
token,
msg.sender,
amount,
balances[token][msg.sender]
);
}
/**
* @notice deposit Ether into the contract
*/
function depositEther() external payable {
require(msg.value > 0);
addUser(msg.sender);
balances[0][msg.sender] = balances[0][msg.sender].add(msg.value);
Deposit(
0,
msg.sender,
msg.value,
balances[0][msg.sender]
);
}
/**
* @notice withdraw funds directly from contract
* @notice must claim by lockme first, after a period of time it would be valid
* @param token The address of withdrawed token, using address(0) to withdraw Ether
* @param amount The amount of token to withdraw
*/
function withdraw(address token, uint256 amount) external {
require(amount > 0);
require(getTime() > userLock[msg.sender] && userLock[msg.sender] != 0);
balances[token][msg.sender] = balances[token][msg.sender].sub(amount);
if (token == 0) {
msg.sender.transfer(amount);
} else {
require(ERC20(token).transfer(msg.sender, amount));
}
Withdraw(
token,
msg.sender,
amount,
balances[token][msg.sender]
);
}
/**
* @notice This function is used to claim to withdraw the funds
* @notice The matching server will automaticlly remove all un-touched orders
* @notice After a period of time, the claimed user can withdraw funds directly from contract without admins involved.
*/
function lockMe() external {
require(userAddress2Id[msg.sender] != 0);
userLock[msg.sender] = getTime() + lockPeriod;
Lock(msg.sender, userLock[msg.sender]);
}
/**
* @notice This function is used to revoke the claim of lockMe
*/
function unlockMe() external {
require(userAddress2Id[msg.sender] != 0);
userLock[msg.sender] = 0;
Lock(msg.sender, 0);
}
/**
* @notice set tradeEventEnabled, only owner
* @param enabled Set tradeEventEnabled if enabled
*/
function setTradeEventEnabled(bool enabled) external onlyOwner {
tradeEventEnabled = enabled;
}
/**
* @notice add/remove a address to admin list, only owner
* @param admin The address of the admin
* @param isAdd Set the address's status in admin list
*/
function addToAdmin(address admin, bool isAdd) external onlyOwner {
isAdmin[admin] = isAdd;
}
/**
* @notice collect the fee to owner's address, only owner
*/
function collectFee(address token) external onlyOwner {
uint256 amount = balances[token][joysoWallet];
require(amount > 0);
balances[token][joysoWallet] = 0;
if (token == 0) {
msg.sender.transfer(amount);
} else {
require(ERC20(token).transfer(msg.sender, amount));
}
Withdraw(
token,
joysoWallet,
amount,
0
);
}
/**
* @notice change lock period, only owner
* @dev can change from 1 days to 30 days, initial is 30 days
*/
function changeLockPeriod(uint256 periodInDays) external onlyOwner {
require(periodInDays <= 30 && periodInDays >= 1);
lockPeriod = periodInDays * 1 days;
}
/**
* @notice add a new token into the token list, only admins
* @dev index 0 & 1 are saved for Ether and JOY
* @dev both index & token can not be redundant, and no removed mathod
* @param tokenAddress token's address
* @param index chosen index of the token
*/
function registerToken(address tokenAddress, uint256 index) external onlyAdmin {
require(index > 1);
require(tokenAddress2Id[tokenAddress] == 0);
require(tokenId2Address[index] == 0);
tokenAddress2Id[tokenAddress] = index;
tokenId2Address[index] = tokenAddress;
}
/**
* @notice withdraw with admins involved, only admin
* @param inputs array of inputs, must have 5 elements
* @dev inputs encoding please reference github wiki
*/
function withdrawByAdmin_Unau(uint256[] inputs) external onlyAdmin {
uint256 amount = inputs[0];
uint256 gasFee = inputs[1];
uint256 data = inputs[2];
uint256 paymentMethod = data & PAYMENT_METHOD_MASK;
address token = tokenId2Address[(data & WITHDRAW_TOKEN_MASK) >> 32];
address user = userId2Address[data & USER_MASK];
bytes32 hash = keccak256(
this,
amount,
gasFee,
data & SIGN_MASK | uint256(token)
);
require(!usedHash[hash]);
require(
verify(
hash,
user,
uint8(data & V_MASK == 0 ? 27 : 28),
bytes32(inputs[3]),
bytes32(inputs[4])
)
);
address gasToken = 0;
if (paymentMethod == PAY_BY_JOY) { // pay fee by JOY
gasToken = joyToken;
} else if (paymentMethod == PAY_BY_TOKEN) { // pay fee by tx token
gasToken = token;
}
if (gasToken == token) { // pay by ether or token
balances[token][user] = balances[token][user].sub(amount.add(gasFee));
} else {
balances[token][user] = balances[token][user].sub(amount);
balances[gasToken][user] = balances[gasToken][user].sub(gasFee);
}
balances[gasToken][joysoWallet] = balances[gasToken][joysoWallet].add(gasFee);
usedHash[hash] = true;
if (token == 0) {
user.transfer(amount);
} else {
require(ERC20(token).transfer(user, amount));
}
}
/**
* @notice match orders with admins involved, only admin
* @param inputs Array of input orders, each order have 6 elements. Inputs must conatin at least 2 orders.
* @dev inputs encoding please reference github wiki
*/
function matchByAdmin_TwH36(uint256[] inputs) external onlyAdmin {
uint256 data = inputs[3];
address user = userId2Address[data & USER_MASK];
// check taker order nonce
require(data >> 224 > userNonce[user]);
address token;
bool isBuy;
(token, isBuy) = decodeOrderTokenAndIsBuy(data);
bytes32 orderHash = keccak256(
this,
inputs[0],
inputs[1],
inputs[2],
data & MATCH_SIGN_MASK | (isBuy ? ORDER_ISBUY : 0) | uint256(token)
);
require(
verify(
orderHash,
user,
uint8(data & V_MASK == 0 ? 27 : 28),
bytes32(inputs[4]),
bytes32(inputs[5])
)
);
uint256 tokenExecute = isBuy ? inputs[1] : inputs[0]; // taker order token execute
tokenExecute = tokenExecute.sub(orderFills[orderHash]);
require(tokenExecute != 0); // the taker order should remain something to trade
uint256 etherExecute = 0; // taker order ether execute
isBuy = !isBuy;
for (uint256 i = 6; i < inputs.length; i += 6) {
//check price, maker price should lower than taker price
require(tokenExecute > 0 && inputs[1].mul(inputs[i + 1]) <= inputs[0].mul(inputs[i]));
data = inputs[i + 3];
user = userId2Address[data & USER_MASK];
// check maker order nonce
require(data >> 224 > userNonce[user]);
bytes32 makerOrderHash = keccak256(
this,
inputs[i],
inputs[i + 1],
inputs[i + 2],
data & MATCH_SIGN_MASK | (isBuy ? ORDER_ISBUY : 0) | uint256(token)
);
require(
verify(
makerOrderHash,
user,
uint8(data & V_MASK == 0 ? 27 : 28),
bytes32(inputs[i + 4]),
bytes32(inputs[i + 5])
)
);
(tokenExecute, etherExecute) = internalTrade(
inputs[i],
inputs[i + 1],
inputs[i + 2],
data,
tokenExecute,
etherExecute,
isBuy,
token,
0,
makerOrderHash
);
}
isBuy = !isBuy;
tokenExecute = isBuy ? inputs[1].sub(tokenExecute) : inputs[0].sub(tokenExecute);
tokenExecute = tokenExecute.sub(orderFills[orderHash]);
processTakerOrder(inputs[2], inputs[3], tokenExecute, etherExecute, isBuy, token, 0, orderHash);
}
/**
* @notice match token orders with admins involved, only admin
* @param inputs Array of input orders, each order have 6 elements. Inputs must conatin at least 2 orders.
* @dev inputs encoding please reference github wiki
*/
function matchTokenOrderByAdmin_k44j(uint256[] inputs) external onlyAdmin {
address user = userId2Address[decodeOrderUserId(inputs[3])];
// check taker order nonce
require(inputs[3] >> 224 > userNonce[user]);
address token;
address base;
bool isBuy;
(token, base, isBuy) = decodeTokenOrderTokenAndIsBuy(inputs[3]);
bytes32 orderHash = getTokenOrderDataHash(inputs, 0, inputs[3], token, base);
require(
verify(
orderHash,
user,
uint8(retrieveV(inputs[3])),
bytes32(inputs[4]),
bytes32(inputs[5])
)
);
uint256 tokenExecute = isBuy ? inputs[1] : inputs[0]; // taker order token execute
tokenExecute = tokenExecute.sub(orderFills[orderHash]);
require(tokenExecute != 0); // the taker order should remain something to trade
uint256 baseExecute = 0; // taker order ether execute
isBuy = !isBuy;
for (uint256 i = 6; i < inputs.length; i += 6) {
//check price, taker price should better than maker price
require(tokenExecute > 0 && inputs[1].mul(inputs[i + 1]) <= inputs[0].mul(inputs[i]));
user = userId2Address[decodeOrderUserId(inputs[i + 3])];
// check maker order nonce
require(inputs[i + 3] >> 224 > userNonce[user]);
bytes32 makerOrderHash = getTokenOrderDataHash(inputs, i, inputs[i + 3], token, base);
require(
verify(
makerOrderHash,
user,
uint8(retrieveV(inputs[i + 3])),
bytes32(inputs[i + 4]),
bytes32(inputs[i + 5])
)
);
(tokenExecute, baseExecute) = internalTrade(
inputs[i],
inputs[i + 1],
inputs[i + 2],
inputs[i + 3],
tokenExecute,
baseExecute,
isBuy,
token,
base,
makerOrderHash
);
}
isBuy = !isBuy;
tokenExecute = isBuy ? inputs[1].sub(tokenExecute) : inputs[0].sub(tokenExecute);
tokenExecute = tokenExecute.sub(orderFills[orderHash]);
processTakerOrder(inputs[2], inputs[3], tokenExecute, baseExecute, isBuy, token, base, orderHash);
}
/**
* @notice update user on-chain nonce with admins involved, only admin
* @param inputs Array of input data, must have 4 elements.
* @dev inputs encoding please reference github wiki
*/
function cancelByAdmin(uint256[] inputs) external onlyAdmin {
uint256 data = inputs[1];
uint256 nonce = data >> 224;
address user = userId2Address[data & USER_MASK];
require(nonce > userNonce[user]);
uint256 gasFee = inputs[0];
require(
verify(
keccak256(this, gasFee, data & SIGN_MASK),
user,
uint8(retrieveV(data)),
bytes32(inputs[2]),
bytes32(inputs[3])
)
);
// update balance
address gasToken = 0;
if (data & PAYMENT_METHOD_MASK == PAY_BY_JOY) {
gasToken = joyToken;
}
require(balances[gasToken][user] >= gasFee);
balances[gasToken][user] = balances[gasToken][user].sub(gasFee);
balances[gasToken][joysoWallet] = balances[gasToken][joysoWallet].add(gasFee);
// update user nonce
userNonce[user] = nonce;
}
/**
* @notice batch send the current balance to the new version contract
* @param inputs Array of input data
* @dev inputs encoding please reference github wiki
*/
function migrateByAdmin_DQV(uint256[] inputs) external onlyAdmin {
uint256 data = inputs[2];
address token = tokenId2Address[(data & WITHDRAW_TOKEN_MASK) >> 32];
address newContract = address(inputs[0]);
for (uint256 i = 1; i < inputs.length; i += 4) {
uint256 gasFee = inputs[i];
data = inputs[i + 1];
address user = userId2Address[data & USER_MASK];
bytes32 hash = keccak256(
this,
gasFee,
data & SIGN_MASK | uint256(token),
newContract
);
require(
verify(
hash,
user,
uint8(data & V_MASK == 0 ? 27 : 28),
bytes32(inputs[i + 2]),
bytes32(inputs[i + 3])
)
);
if (gasFee > 0) {
uint256 paymentMethod = data & PAYMENT_METHOD_MASK;
if (paymentMethod == PAY_BY_JOY) {
balances[joyToken][user] = balances[joyToken][user].sub(gasFee);
balances[joyToken][joysoWallet] = balances[joyToken][joysoWallet].add(gasFee);
} else if (paymentMethod == PAY_BY_TOKEN) {
balances[token][user] = balances[token][user].sub(gasFee);
balances[token][joysoWallet] = balances[token][joysoWallet].add(gasFee);
} else {
balances[0][user] = balances[0][user].sub(gasFee);
balances[0][joysoWallet] = balances[0][joysoWallet].add(gasFee);
}
}
uint256 amount = balances[token][user];
balances[token][user] = 0;
if (token == 0) {
Migratable(newContract).migrate.value(amount)(user, amount, token);
} else {
ERC20(token).approve(newContract, amount);
Migratable(newContract).migrate(user, amount, token);
}
}
}
/**
* @notice transfer token from admin to users
* @param token address of token
* @param account receiver's address
* @param amount amount to transfer
*/
function transferForAdmin(address token, address account, uint256 amount) onlyAdmin external {
require(tokenAddress2Id[token] != 0);
require(userAddress2Id[msg.sender] != 0);
addUser(account);
balances[token][msg.sender] = balances[token][msg.sender].sub(amount);
balances[token][account] = balances[token][account].add(amount);
}
/**
* @notice get balance information
* @param token address of token
* @param account address of user
*/
function getBalance(address token, address account) external view returns (uint256) {
return balances[token][account];
}
/**
* @dev get tokenId and check the order is a buy order or not, internal
* tokenId take 4 bytes
* isBuy is true means this order is buying token
*/
function decodeOrderTokenAndIsBuy(uint256 data) internal view returns (address token, bool isBuy) {
uint256 tokenId = (data & TOKEN_SELL_MASK) >> 48;
if (tokenId == 0) {
token = tokenId2Address[(data & TOKEN_BUY_MASK) >> 32];
isBuy = true;
} else {
token = tokenId2Address[tokenId];
}
}
/**
* @dev decode token oreder data, internal
*/
function decodeTokenOrderTokenAndIsBuy(uint256 data) internal view returns (address token, address base, bool isBuy) {
isBuy = data & IS_BUY_MASK == ORDER_ISBUY;
if (isBuy) {
token = tokenId2Address[(data & TOKEN_BUY_MASK) >> 32];
base = tokenId2Address[(data & TOKEN_SELL_MASK) >> 48];
} else {
token = tokenId2Address[(data & TOKEN_SELL_MASK) >> 48];
base = tokenId2Address[(data & TOKEN_BUY_MASK) >> 32];
}
}
function getTime() internal view returns (uint256) {
return now;
}
/**
* @dev get token order's hash for user to sign, internal
* @param inputs forword tokenOrderMatch's input to this function
* @param offset offset of the order in inputs
*/
function getTokenOrderDataHash(uint256[] inputs, uint256 offset, uint256 data, address token, address base) internal view returns (bytes32) {
return keccak256(
this,
inputs[offset],
inputs[offset + 1],
inputs[offset + 2],
data & SIGN_MASK | uint256(token),
base,
(data & TOKEN_JOY_PRICE_MASK) >> 64
);
}
/**
* @dev check if the provided signature is valid, internal
* @param hash signed information
* @param sender signer address
* @param v sig_v
* @param r sig_r
* @param s sig_s
*/
function verify(bytes32 hash, address sender, uint8 v, bytes32 r, bytes32 s) internal pure returns (bool) {
return ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) == sender;
}
/**
* @dev give a new user an id, intrnal
*/
function addUser(address _address) internal {
if (userAddress2Id[_address] != 0) {
return;
}
userCount += 1;
userAddress2Id[_address] = userCount;
userId2Address[userCount] = _address;
NewUser(_address, userCount);
}
function processTakerOrder(
uint256 gasFee,
uint256 data,
uint256 tokenExecute,
uint256 baseExecute,
bool isBuy,
address token,
address base,
bytes32 orderHash
)
internal
{
uint256 fee = calculateFee(gasFee, data, baseExecute, orderHash, true, base == 0);
updateUserBalance(data, isBuy, baseExecute, tokenExecute, fee, token, base);
orderFills[orderHash] = orderFills[orderHash].add(tokenExecute);
if (tradeEventEnabled) {
TradeSuccess(userId2Address[data & USER_MASK], baseExecute, tokenExecute, isBuy, fee);
}
}
function internalTrade(
uint256 amountSell,
uint256 amountBuy,
uint256 gasFee,
uint256 data,
uint256 _remainingToken,
uint256 _baseExecute,
bool isBuy,
address token,
address base,
bytes32 orderHash
)
internal returns (uint256 remainingToken, uint256 baseExecute)
{
uint256 tokenGet = calculateTokenGet(amountSell, amountBuy, _remainingToken, isBuy, orderHash);
uint256 baseGet = calculateBaseGet(amountSell, amountBuy, isBuy, tokenGet);
uint256 fee = calculateFee(gasFee, data, baseGet, orderHash, false, base == 0);
updateUserBalance(data, isBuy, baseGet, tokenGet, fee, token, base);
orderFills[orderHash] = orderFills[orderHash].add(tokenGet);
remainingToken = _remainingToken.sub(tokenGet);
baseExecute = _baseExecute.add(baseGet);
if (tradeEventEnabled) {
TradeSuccess(
userId2Address[data & USER_MASK],
baseGet,
tokenGet,
isBuy,
fee
);
}
}
function updateUserBalance(
uint256 data,
bool isBuy,
uint256 baseGet,
uint256 tokenGet,
uint256 fee,
address token,
address base
)
internal
{
address user = userId2Address[data & USER_MASK];
uint256 baseFee = fee;
uint256 joyFee = 0;
if ((base == 0 ? (data & JOY_PRICE_MASK) >> 164 : (data & TOKEN_JOY_PRICE_MASK) >> 64) != 0) {
joyFee = fee;
baseFee = 0;
}
if (isBuy) { // buy token, sell ether
balances[base][user] = balances[base][user].sub(baseGet).sub(baseFee);
balances[token][user] = balances[token][user].add(tokenGet);
} else {
balances[base][user] = balances[base][user].add(baseGet).sub(baseFee);
balances[token][user] = balances[token][user].sub(tokenGet);
}
if (joyFee != 0) {
balances[joyToken][user] = balances[joyToken][user].sub(joyFee);
balances[joyToken][joysoWallet] = balances[joyToken][joysoWallet].add(joyFee);
} else {
balances[base][joysoWallet] = balances[base][joysoWallet].add(baseFee);
}
}
function calculateFee(
uint256 gasFee,
uint256 data,
uint256 baseGet,
bytes32 orderHash,
bool isTaker,
bool isEthOrder
)
internal view returns (uint256)
{
uint256 fee = orderFills[orderHash] == 0 ? gasFee : 0;
uint256 txFee = baseGet.mul(isTaker ? (data & TAKER_FEE_MASK) >> 208 : (data & MAKER_FEE_MASK) >> 192) / 10000;
uint256 joyPrice = isEthOrder ? (data & JOY_PRICE_MASK) >> 164 : (data & TOKEN_JOY_PRICE_MASK) >> 64;
if (joyPrice != 0) {
txFee = isEthOrder ? txFee / (10 ** 5) / joyPrice : txFee * (10 ** 12) / joyPrice;
}
return fee.add(txFee);
}
function calculateBaseGet(
uint256 amountSell,
uint256 amountBuy,
bool isBuy,
uint256 tokenGet
)
internal pure returns (uint256)
{
return isBuy ? tokenGet.mul(amountSell) / amountBuy : tokenGet.mul(amountBuy) / amountSell;
}
function calculateTokenGet(
uint256 amountSell,
uint256 amountBuy,
uint256 remainingToken,
bool isBuy,
bytes32 orderHash
)
internal view returns (uint256)
{
uint256 makerRemainingToken = isBuy ? amountBuy : amountSell;
makerRemainingToken = makerRemainingToken.sub(orderFills[orderHash]);
require(makerRemainingToken > 0); // the maker order should remain something to trade
return makerRemainingToken >= remainingToken ? remainingToken : makerRemainingToken;
}
}
| * @notice collect the fee to owner's address, only owner/ | function collectFee(address token) external onlyOwner {
uint256 amount = balances[token][joysoWallet];
require(amount > 0);
balances[token][joysoWallet] = 0;
if (token == 0) {
msg.sender.transfer(amount);
require(ERC20(token).transfer(msg.sender, amount));
}
Withdraw(
token,
joysoWallet,
amount,
0
);
}
| 900,932 | [
1,
14676,
326,
14036,
358,
3410,
1807,
1758,
16,
1338,
3410,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
3274,
14667,
12,
2867,
1147,
13,
3903,
1338,
5541,
288,
203,
3639,
2254,
5034,
3844,
273,
324,
26488,
63,
2316,
6362,
30952,
1900,
83,
16936,
15533,
203,
3639,
2583,
12,
8949,
405,
374,
1769,
203,
3639,
324,
26488,
63,
2316,
6362,
30952,
1900,
83,
16936,
65,
273,
374,
31,
203,
3639,
309,
261,
2316,
422,
374,
13,
288,
203,
5411,
1234,
18,
15330,
18,
13866,
12,
8949,
1769,
203,
5411,
2583,
12,
654,
39,
3462,
12,
2316,
2934,
13866,
12,
3576,
18,
15330,
16,
3844,
10019,
203,
3639,
289,
203,
3639,
3423,
9446,
12,
203,
5411,
1147,
16,
203,
5411,
525,
83,
1900,
83,
16936,
16,
203,
5411,
3844,
16,
203,
5411,
374,
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
]
|
/**
* DELFI is an on-chain price oracle you can reason about
* it provides a liquidity-weighted index of ETH/DAI prices from decentralized exchanges
* the price is backed up by the ETH amount required to move the rate more than 5%
* this provides a quantifiable threshold of economic activity the price can safely support
___---___
___---___---___---___
___---___--- ---___---___
___---___--- ---___---___
___---___--- D E L F I ---___---___
___---___--- eth/dai ---___---___
__---___---_________________________________________________________---___---__
===============================================================================
|||| ||||
|---------------------------------------------------------------------------|
|___-----___-----___-----___-----___-----___-----___-----___-----___-----___|
/ _ \===/ _ \ / _ \===/ _ \ / _ \===/ _ \ / _ \===/ _ \ / _ \===/ _ \
( (.\ oOo /.) ) ( (.\ oOo /.) ) ( (.\ oOo /.) ) ( (.\ oOo /.) ) ( (.\ oOo /.) )
\__/=====\__/ \__/=====\__/ \__/=====\__/ \__/=====\__/ \__/=====\__/
||||||| ||||||| ||||||| ||||||| |||||||
||||||| ||||||| ||||||| ||||||| |||||||
||||||| ||||||| ||||||| ||||||| |||||||
||||||| ||||||| ||||||| ||||||| |||||||
||||||| ||||||| ||||||| ||||||| |||||||
||||||| ||||||| ||||||| ||||||| |||||||
||||||| ||||||| ||||||| ||||||| |||||||
||||||| ||||||| ||||||| ||||||| |||||||
(oOoOo) (oOoOo) (oOoOo) (oOoOo) (oOoOo)
J%%%%%L J%%%%%L J%%%%%L J%%%%%L J%%%%%L
ZZZZZZZZZ ZZZZZZZZZ ZZZZZZZZZ ZZZZZZZZZ ZZZZZZZZZ
===========================================================================
__|_________________________________________________________________________|__
_|___________________________________________________________________________|_
|_____________________________________________________________________________|
_______________________________________________________________________________
*/
pragma solidity ^0.5.4;
//////////////
//INTERFACES//
//////////////
contract ERC20 {
function balanceOf(address) external view returns(uint256) {}
}
contract Uniswap {
function getEthToTokenInputPrice(uint256) external view returns(uint256) {}
function getTokenToEthOutputPrice(uint256) external view returns(uint256) {}
}
contract Eth2Dai {
function getBuyAmount(address, address, uint256) external view returns(uint256) {}
function getPayAmount(address, address, uint256) external view returns(uint256) {}
}
contract Bancor {
function getReturn(address, address, uint256) external view returns(uint256, uint256) {}
}
contract BancorDai {
function getReturn(address, address, uint256) external view returns(uint256) {}
}
contract Kyber {
function searchBestRate(address, address, uint256, bool) external view returns(address, uint256) {}
}
/////////////////
//MAIN CONTRACT//
/////////////////
contract Delfi {
///////////////////
//STATE VARIABLES//
///////////////////
/** latest ETH/DAI price */
uint256 public latestRate;
/** block number of latest state update */
uint256 public latestBlock;
/** latest cost to move the price 5% */
uint256 public latestCostToMovePrice;
uint256 constant public ONE_ETH = 10**18;
uint256 constant public FIVE_PERCENT = 5;
address constant public DAI = 0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359;
address constant public WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address constant public BNT = 0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C;
address constant public UNISWAP = 0x09cabEC1eAd1c0Ba254B09efb3EE13841712bE14;
address constant public ETH2DAI = 0x39755357759cE0d7f32dC8dC45414CCa409AE24e;
address constant public BANCOR = 0xCBc6a023eb975a1e2630223a7959988948E664f3;
address constant public BANCORDAI = 0x587044b74004E3D5eF2D453b7F8d198d9e4cB558;
address constant public BANCORETH = 0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315;
address constant public KYBER = 0x9ae49C0d7F8F9EF4B864e004FE86Ac8294E20950;
address constant public KYBERETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address constant public KYBER_OASIS_RESERVE = 0x04A487aFd662c4F9DEAcC07A7B10cFb686B682A4;
address constant public KYBER_UNISWAP_RESERVE = 0x13032DeB2d37556cf49301f713E9d7e1d1A8b169;
///////////////////////////
//CONTRACT INSTANTIATIONS//
///////////////////////////
ERC20 constant dai = ERC20(DAI);
Uniswap constant uniswap = Uniswap(UNISWAP);
Eth2Dai constant eth2dai = Eth2Dai(ETH2DAI);
Bancor constant bancor = Bancor(BANCOR);
BancorDai constant bancordai = BancorDai(BANCORDAI);
Kyber constant kyber = Kyber(KYBER);
///////////////
//CONSTRUCTOR//
///////////////
constructor() public {
/** set intial values */
updateCurrentRate();
}
///////////
//METHODS//
///////////
/**
* get the DAI balance of an address
* @param _owner address of token holder
* @return _tokenAmount token balance of holder in smallest unit
*/
function getDaiBalance(
address _owner
)
public
view
returns(
uint256 _tokenAmount
) {
return dai.balanceOf(_owner);
}
/**
* get the non-token ETH balance of an address
* @param _owner address to check
* @return _ethAmount amount in wei
*/
function getEthBalance(
address _owner
)
public
view
returns(
uint256 _ethAmount
) {
return _owner.balance;
}
/**
* get the buy price of DAI on uniswap
* @param _ethAmount amount of ETH being spent in wei
* @return _rate returned as a rate in wei
*/
function getUniswapBuyPrice(
uint256 _ethAmount
)
public
view
returns(
uint256 _rate
) {
uint256 tokenAmount = uniswap.getEthToTokenInputPrice(_ethAmount);
return (tokenAmount * ONE_ETH) / _ethAmount;
}
/**
* get the sell price of DAI on uniswap
* @param _ethAmount amount of ETH being purchased in wei
* @return _rate returned as a rate in wei
*/
function getUniswapSellPrice(
uint256 _ethAmount
)
public
view
returns(
uint256 _rate
) {
uint256 ethAmount = uniswap.getTokenToEthOutputPrice(_ethAmount);
return (ethAmount * ONE_ETH) / _ethAmount;
}
/**
* get the buy price of DAI on Eth2Dai
* @param _ethAmount amount of ETH being spent in wei
* @return _rate returned as a rate in wei
*/
function getEth2DaiBuyPrice(
uint256 _ethAmount
)
public
view
returns(
uint256 _rate
) {
uint256 tokenAmount = eth2dai.getBuyAmount(DAI, WETH, _ethAmount);
return (tokenAmount * ONE_ETH) / _ethAmount;
}
/**
* get the sell price of DAI on Eth2Dai
* @param _ethAmount amount of ETH being purchased in wei
* @return _rate returned as a rate in wei
*/
function getEth2DaiSellPrice(
uint256 _ethAmount
)
public
view
returns(
uint256 _rate
) {
uint256 ethAmount = eth2dai.getPayAmount(DAI, WETH, _ethAmount);
return (ethAmount * ONE_ETH) / _ethAmount;
}
/**
* get the buy price of DAI on Bancor
* @param _ethAmount amount of ETH being spent in wei
* @return _rate returned as a rate in wei
*/
function getBancorBuyPrice(
uint256 _ethAmount
)
public
view
returns(
uint256 _rate
) {
/** convert from eth to bnt */
/** parse tuple return value */
uint256 bntAmount;
(bntAmount,) = bancor.getReturn(BANCORETH, BNT, _ethAmount);
/** convert from bnt to eth */
uint256 tokenAmount = bancordai.getReturn(BNT, DAI, bntAmount);
return (tokenAmount * ONE_ETH) / _ethAmount;
}
/**
* get the sell price of DAI on Bancor
* @param _ethAmount amount of ETH being purchased in wei
* @return _rate returned as a rate in wei
*/
function getBancorSellPrice(
uint256 _ethAmount
)
public
view
returns(
uint256 _rate
) {
uint256 roughTokenAmount = (latestRate * _ethAmount) / ONE_ETH;
/** convert from dai to bnt*/
uint256 bntAmount = bancordai.getReturn(DAI, BNT, roughTokenAmount);
/** convert from bnt to eth */
/** parse tuple return value */
uint256 ethAmount;
(ethAmount,) = bancor.getReturn(BNT, BANCORETH, bntAmount);
return (ONE_ETH * roughTokenAmount) / ethAmount;
}
/**
* get the buy price of DAI on Kyber
* @param _ethAmount amount of ETH being spent in wei
* @return _reserveAddress reserve address with best rate
* @return _rate returned as a rate in wei
*/
function getKyberBuyPrice(
uint256 _ethAmount
)
public
view
returns(
address _reserveAddress,
uint256 _rate
) {
return kyber.searchBestRate(KYBERETH, DAI, _ethAmount, true);
}
/**
* get the sell price of DAI on Kyber
* @param _ethAmount amount of ETH being purchased in wei
* @return _reserveAddress reserve address with best rate
* @return _rate returned as a rate in wei
*/
function getKyberSellPrice(
uint256 _ethAmount
)
public
view
returns(
address _reserveAddress,
uint256 _rate
) {
/** get an approximate token amount to calculate ETH returned */
/** if there is no recent price, calc current kyber buy price */
uint256 recentRate;
if (block.number > latestRate + 100) {
(,recentRate) = getKyberBuyPrice(_ethAmount);
} else {
recentRate = latestRate;
}
uint256 ethAmount;
address reserveAddress;
(reserveAddress, ethAmount) = kyber.searchBestRate(DAI, KYBERETH, _ethAmount, true);
uint256 tokenAmount = (_ethAmount * ONE_ETH) / ethAmount;
return (reserveAddress, (tokenAmount * ONE_ETH) / _ethAmount);
}
/**
* get the most recent saved rate
* cheap to call but information may be outdated
* @return _rate most recent saved ETH/DAI rate in wei
* @return _block block.number the most recent state was saved
* @return _costToMoveFivePercent cost to move the price 5% in wei
*/
function getLatestSavedRate()
view
public
returns(
uint256 _rate,
uint256 _block,
uint256 _costToMoveFivePercent
) {
return (latestRate, latestBlock, latestCostToMovePrice);
}
/**
* updates the price information to the current block and returns this information
* comparatively expensive to call but always up to date
* @return _rate most recent saved ETH/DAI rate in wei
* @return _block block.number the most recent state was saved
* @return _costToMoveFivePercent cost to move the price 5% in wei
*/
function getLatestRate()
external
returns(
uint256 _rate,
uint256 _block,
uint256 _costToMoveFivePercent
) {
updateCurrentRate();
return (latestRate, latestBlock, latestCostToMovePrice);
}
//////////////////////
//INTERNAL FUNCTIONS//
//////////////////////
/**
* updates the current rate in state
* @return _rate most recent saved ETH/DAI rate in wei
* @return _costToMoveFivePercent cost to move the price 5% in wei
*/
function updateCurrentRate()
internal
returns(
uint256 _rate,
uint256 _costToMoveFivePercent
) {
/** find midpoints of each spread */
uint256[3] memory midPointArray = [
findMidPoint(getUniswapBuyPrice(ONE_ETH), getUniswapSellPrice(ONE_ETH)),
findMidPoint(getBancorBuyPrice(ONE_ETH), getBancorBuyPrice(ONE_ETH)),
findMidPoint(getEth2DaiBuyPrice(ONE_ETH), getEth2DaiSellPrice(ONE_ETH))
];
/** find liquidity of pooled exchanges */
uint256 uniswapLiquidity = getEthBalance(UNISWAP);
uint256 bancorLiquidity = getDaiBalance(BANCORDAI) * ONE_ETH / midPointArray[1];
uint256 eth2daiRoughLiquidity = getDaiBalance(ETH2DAI) * ONE_ETH / midPointArray[2];
/** cost of percent move for pooled exchanges */
/** 2.5% of liquidity is approximately a 5% price move */
uint256 costToMovePriceUniswap = (uniswapLiquidity * FIVE_PERCENT) / 50;
uint256 costToMovePriceBancor = (bancorLiquidity * FIVE_PERCENT) / 50;
/** divide by price difference */
uint256 largeBuy = eth2daiRoughLiquidity / 2;
uint256 priceMove = getEth2DaiBuyPrice(largeBuy);
uint256 priceMovePercent = ((midPointArray[2] * 10000) / priceMove) - 10000;
/** ensure largeBuy causes a price move more than _percent */
/** increase large buy amount if necessary */
if (priceMovePercent < FIVE_PERCENT * 100) {
largeBuy += eth2daiRoughLiquidity - 1;
priceMove = getEth2DaiBuyPrice(largeBuy);
priceMovePercent = ((midPointArray[2] * 10000) / priceMove) - 10000;
}
uint256 ratioOfPriceMove = FIVE_PERCENT * 10000 / priceMovePercent;
uint256 costToMovePriceEth2Dai = largeBuy * ratioOfPriceMove / 100;
/** information stored in memory arrays to avoid stack depth issues */
uint256[3] memory costOfPercentMoveArray = [costToMovePriceUniswap, costToMovePriceBancor, costToMovePriceEth2Dai];
return calcRatio(midPointArray, costOfPercentMoveArray);
}
/**
* extension of previous method used to update state
* @return _rate most recent saved ETH/DAI rate in wei
* @return _costToMoveFivePercent cost to move the price 5% in wei
*/
function calcRatio(
uint256[3] memory _midPointArray,
uint256[3] memory _costOfPercentMoveArray
)
internal
returns(
uint256 _rate,
uint256 _costToMoveFivePercent
)
{
uint256 totalCostOfPercentMove = _costOfPercentMoveArray[0] + _costOfPercentMoveArray[1] + _costOfPercentMoveArray[2];
/** calculate proportion of each exchange in the formula */
/** precise to two decimals */
uint256 precision = 10000;
uint256[3] memory propotionArray;
propotionArray[0] = (_costOfPercentMoveArray[0] * precision) / totalCostOfPercentMove;
propotionArray[1] = (_costOfPercentMoveArray[1] * precision) / totalCostOfPercentMove;
propotionArray[2] = (_costOfPercentMoveArray[2] * precision) / totalCostOfPercentMove;
/** balance prices */
uint256 balancedRate =
(
(_midPointArray[0] * propotionArray[0]) +
(_midPointArray[1] * propotionArray[1]) +
(_midPointArray[2] * propotionArray[2])
)
/ precision;
latestRate = balancedRate;
latestBlock = block.number;
latestCostToMovePrice = totalCostOfPercentMove;
return (balancedRate, totalCostOfPercentMove);
}
/**
* utility function to find mean of an array of values
* no safe math, yolo
* @param _a first value
* @param _b second value
* @return _midpoint average value
*/
function findMidPoint(
uint256 _a,
uint256 _b
)
internal
pure
returns(
uint256 _midpoint
) {
return (_a + _b) / 2;
}
////////////
//FALLBACK//
////////////
/**
* non-payable fallback function
* this is redundant but more explicit than not including a fallback
*/
function() external {}
} | * non-payable fallback function this is redundant but more explicit than not including a fallback/ | function() external {}
| 5,377,081 | [
1,
5836,
17,
10239,
429,
5922,
445,
333,
353,
19530,
1496,
1898,
5515,
2353,
486,
6508,
279,
5922,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
915,
1435,
3903,
2618,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xbc6a1af02c09fc1514B95eC98756ccAa95e8Af2e/sources/GEtherBridge.sol | * @notice Allows for the beforehand calculation of shares to be received/minted upon depositing to the contract. @param _cost The amount of reserve token being deposited. @param _totalReserve The reserve balance as obtained by totalReserve(). @param _totalSupply The shares supply as obtained by totalSupply(). @param _depositFee The current deposit fee as obtained by depositFee(). @return _netShares The net amount of shares being received. @return _feeShares The fee amount of shares being deducted./ | function calcDepositSharesFromCost(uint256 _cost, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee) public pure override returns (uint256 _netShares, uint256 _feeShares)
{
return GFormulae._calcDepositSharesFromCost(_cost, _totalReserve, _totalSupply, _depositFee);
}
| 2,650,898 | [
1,
19132,
364,
326,
1865,
2349,
11096,
434,
24123,
358,
506,
540,
5079,
19,
81,
474,
329,
12318,
443,
1724,
310,
358,
326,
6835,
18,
225,
389,
12398,
1021,
3844,
434,
20501,
1147,
3832,
443,
1724,
329,
18,
225,
389,
4963,
607,
6527,
1021,
20501,
11013,
487,
12700,
635,
2078,
607,
6527,
7675,
225,
389,
4963,
3088,
1283,
1021,
24123,
14467,
487,
12700,
635,
2078,
3088,
1283,
7675,
225,
389,
323,
1724,
14667,
1021,
783,
443,
1724,
14036,
487,
12700,
635,
443,
1724,
14667,
7675,
327,
389,
2758,
24051,
1021,
2901,
3844,
434,
24123,
3832,
5079,
18,
327,
389,
21386,
24051,
1021,
14036,
3844,
434,
24123,
3832,
11140,
853,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
915,
7029,
758,
1724,
24051,
1265,
8018,
12,
11890,
5034,
389,
12398,
16,
2254,
5034,
389,
4963,
607,
6527,
16,
2254,
5034,
389,
4963,
3088,
1283,
16,
2254,
5034,
389,
323,
1724,
14667,
13,
1071,
16618,
3849,
1135,
261,
11890,
5034,
389,
2758,
24051,
16,
2254,
5034,
389,
21386,
24051,
13,
203,
202,
95,
203,
202,
202,
2463,
611,
14972,
73,
6315,
12448,
758,
1724,
24051,
1265,
8018,
24899,
12398,
16,
389,
4963,
607,
6527,
16,
389,
4963,
3088,
1283,
16,
389,
323,
1724,
14667,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity =0.8.10;
import "../auth/AdminAuth.sol";
import "../interfaces/IProxyRegistry.sol";
import "../interfaces/IDSProxy.sol";
import "./helpers/UtilHelper.sol";
/// @title Checks Mcd registry and replaces the proxy addr if owner changed
contract DFSProxyRegistry is AdminAuth, UtilHelper {
IProxyRegistry public mcdRegistry = IProxyRegistry(MKR_PROXY_REGISTRY);
mapping(address => address) public changedOwners;
mapping(address => address[]) public additionalProxies;
/// @notice Changes the proxy that is returned for the user
/// @dev Used when the user changed DSProxy ownership himself
function changeMcdOwner(address _user, address _proxy) public onlyOwner {
if (IDSProxy(_proxy).owner() == _user) {
changedOwners[_user] = _proxy;
}
}
/// @notice Returns the proxy address associated with the user account
/// @dev If user changed ownership of DSProxy admin can hardcode replacement
function getMcdProxy(address _user) public view returns (address) {
address proxyAddr = mcdRegistry.proxies(_user);
// if check changed proxies
if (changedOwners[_user] != address(0)) {
return changedOwners[_user];
}
return proxyAddr;
}
function addAdditionalProxy(address _user, address _proxy) public onlyOwner {
if (IDSProxy(_proxy).owner() == _user) {
additionalProxies[_user].push(_proxy);
}
}
function getAllProxies(address _user) public view returns (address, address[] memory) {
return (getMcdProxy(_user), additionalProxies[_user]);
}
} | @title Checks Mcd registry and replaces the proxy addr if owner changed | contract DFSProxyRegistry is AdminAuth, UtilHelper {
IProxyRegistry public mcdRegistry = IProxyRegistry(MKR_PROXY_REGISTRY);
mapping(address => address) public changedOwners;
mapping(address => address[]) public additionalProxies;
function changeMcdOwner(address _user, address _proxy) public onlyOwner {
if (IDSProxy(_proxy).owner() == _user) {
changedOwners[_user] = _proxy;
}
}
function changeMcdOwner(address _user, address _proxy) public onlyOwner {
if (IDSProxy(_proxy).owner() == _user) {
changedOwners[_user] = _proxy;
}
}
function getMcdProxy(address _user) public view returns (address) {
address proxyAddr = mcdRegistry.proxies(_user);
if (changedOwners[_user] != address(0)) {
return changedOwners[_user];
}
return proxyAddr;
}
function getMcdProxy(address _user) public view returns (address) {
address proxyAddr = mcdRegistry.proxies(_user);
if (changedOwners[_user] != address(0)) {
return changedOwners[_user];
}
return proxyAddr;
}
function addAdditionalProxy(address _user, address _proxy) public onlyOwner {
if (IDSProxy(_proxy).owner() == _user) {
additionalProxies[_user].push(_proxy);
}
}
function addAdditionalProxy(address _user, address _proxy) public onlyOwner {
if (IDSProxy(_proxy).owner() == _user) {
additionalProxies[_user].push(_proxy);
}
}
function getAllProxies(address _user) public view returns (address, address[] memory) {
return (getMcdProxy(_user), additionalProxies[_user]);
}
} | 6,382,019 | [
1,
4081,
490,
4315,
4023,
471,
12878,
326,
2889,
3091,
309,
3410,
3550,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
23872,
3886,
4243,
353,
7807,
1730,
16,
3564,
2276,
288,
203,
565,
467,
3886,
4243,
1071,
312,
4315,
4243,
273,
467,
3886,
4243,
12,
49,
47,
54,
67,
16085,
67,
5937,
25042,
1769,
203,
203,
565,
2874,
12,
2867,
516,
1758,
13,
1071,
3550,
5460,
414,
31,
203,
565,
2874,
12,
2867,
516,
1758,
63,
5717,
1071,
3312,
21488,
31,
203,
203,
203,
565,
445,
2549,
49,
4315,
5541,
12,
2867,
389,
1355,
16,
1758,
389,
5656,
13,
1071,
1338,
5541,
288,
203,
3639,
309,
261,
19516,
3886,
24899,
5656,
2934,
8443,
1435,
422,
389,
1355,
13,
288,
203,
5411,
3550,
5460,
414,
63,
67,
1355,
65,
273,
389,
5656,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
2549,
49,
4315,
5541,
12,
2867,
389,
1355,
16,
1758,
389,
5656,
13,
1071,
1338,
5541,
288,
203,
3639,
309,
261,
19516,
3886,
24899,
5656,
2934,
8443,
1435,
422,
389,
1355,
13,
288,
203,
5411,
3550,
5460,
414,
63,
67,
1355,
65,
273,
389,
5656,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
2108,
4315,
3886,
12,
2867,
389,
1355,
13,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
1758,
2889,
3178,
273,
312,
4315,
4243,
18,
20314,
606,
24899,
1355,
1769,
203,
203,
3639,
309,
261,
6703,
5460,
414,
63,
67,
1355,
65,
480,
1758,
12,
20,
3719,
288,
203,
5411,
327,
3550,
5460,
414,
63,
67,
1355,
15533,
203,
3639,
289,
203,
203,
3639,
327,
2889,
3178,
31,
203,
565,
289,
203,
203,
565,
445,
2108,
2
]
|
pragma solidity >=0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
address[] private registeredAirlines;
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
string flight_name;
}
struct Airline{
address airline;
string airline_name;
bool isRegistered;
bool fundsSubmitted;
uint256 registeredvotes;
}
struct Insurance{
address payable insuree;
uint256 funds;
}
mapping(bytes32 => Flight) private flights;
mapping(address => Airline) private airlines;
mapping(address=>bool) private airlineauthorised;
mapping(bytes32=>Insurance[]) private policies;
mapping(bytes32 => bool) private airlineRegistrationVotes;
mapping(address => uint256) private credits;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event AirlineAdded(address airline);
event AirlineVoted(address airlinevoter,address airlinevotee);
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
)
public
{
contractOwner = msg.sender;
airlineauthorised[msg.sender]=true;
}
/********************************************************************************************/
/* 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");
_;
}
modifier requireAuthorizedCaller() {
require(
airlineauthorised[msg.sender] == true,
"Requires caller is authorized to call this function");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view requireAuthorizedCaller
returns(bool) {
return operational;
}
//Check for airline addition
function IsAirlineAdded(
address airline
)
external
view
requireAuthorizedCaller
requireIsOperational
returns (bool)
{
return airlines[airline].airline == airline;
}
//Check for airline Registration
function IsAirlineRegistered(
address airline
)
external
view
requireAuthorizedCaller
requireIsOperational
returns (bool)
{
return airlines[airline].isRegistered;
}
function hasAirlineSubmittedFunds(
address airline
)
external
view
requireAuthorizedCaller
requireIsOperational
returns (bool)
{
return airlines[airline].fundsSubmitted == true;
}
function hasAirlineVoted(
address airlinevoter,
address airlinevotee
)
external
view
requireAuthorizedCaller
requireIsOperational
returns (bool)
{
bytes32 voteHash = keccak256(
abi.encodePacked(airlinevoter, airlinevotee));
return airlineRegistrationVotes[voteHash] == true;
}
//Getting the complete list of airlines
function getRegisteredAirlines(
)
external
view
requireAuthorizedCaller
requireIsOperational
returns (address[] memory)
{
return registeredAirlines;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner
{
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function authorizeCaller(address caller) external requireContractOwner {
airlineauthorised[caller] = true;
}
function deauthorizeCaller(address caller) external requireContractOwner {
airlineauthorised[caller] = false;
}
function addAirline(address airline,
string calldata airline_name
) external
requireAuthorizedCaller
requireIsOperational
{
airlines[airline] = Airline({
airline: airline,
airline_name: airline_name,
isRegistered: false,
fundsSubmitted: false,
registeredvotes:0
});
emit AirlineAdded(airline);
}
function registerAirline
( address airline
)
external
requireAuthorizedCaller
requireIsOperational
{
airlines[airline].isRegistered = true;
registeredAirlines.push(airline);
}
function registerFlight(
address airline,
string calldata flight_name,
uint256 timestamp
)
external
requireAuthorizedCaller
requireIsOperational
{
flights[getFlightKey(airline, flight_name, timestamp)] = Flight({
isRegistered: true,
statusCode: 0,
updatedTimestamp: timestamp,
airline: airline,
flight_name: flight_name
});
}
function AirlineVote(
address airlinevoter,
address airlinevotee
)
external
requireAuthorizedCaller
requireIsOperational
returns (uint256)
{
bytes32 vote = keccak256(
abi.encodePacked(airlinevoter
, airlinevotee));
airlineRegistrationVotes[vote] = true;
airlines[airlinevotee].registeredvotes += 1;
emit AirlineVoted(airlinevoter,airlinevotee);
return airlines[airlinevotee].registeredvotes;
}
function AirlinefundsSubmitted(
address airline
)
external
requireAuthorizedCaller
requireIsOperational
{
airlines[airline].fundsSubmitted = true;
}
/**
* @dev Buy insurance for a flight
*
*/
function buyInsurancePolicy(
address airline,
string calldata flight_name,
address payable _insuree,
uint256 amount
)
external
requireAuthorizedCaller
requireIsOperational
{
policies[keccak256(abi.encodePacked(airline, flight_name))].push(
Insurance({
insuree: _insuree,
funds: amount
})
);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(
address airline,
string calldata flight,
uint256 creditMultiplier
)
external
requireAuthorizedCaller
requireIsOperational
{
bytes32 policyKey = keccak256(abi.encodePacked(airline, flight));
Insurance[] memory policiesToCredit = policies[policyKey];
uint256 currentCredits;
for (uint i = 0; i < policiesToCredit.length; i++) {
currentCredits = credits[policiesToCredit[i].insuree];
// Calculate payout with multiplier and add to existing credits
uint256 creditsPayout = (
policiesToCredit[i].funds.mul(creditMultiplier).div(10));
credits[policiesToCredit[i].insuree] = currentCredits.add(
creditsPayout);
}
delete policies[policyKey];
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function payToInsuree
(
address payable insuree
)
external
requireAuthorizedCaller
requireIsOperational
{
uint256 creditsAvailable = credits[insuree];
require(creditsAvailable > 0, "Requires credits are available");
credits[insuree] = 0;
insuree.transfer(creditsAvailable);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
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 {}
}
| * @dev Get operating status of contract @return A bool that is the current operating status/ | function isOperational()
public
view requireAuthorizedCaller
returns(bool) {
return operational;
}
| 12,680,659 | [
1,
967,
16929,
1267,
434,
6835,
327,
432,
1426,
716,
353,
326,
783,
16929,
1267,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
353,
2988,
287,
1435,
7010,
18701,
1071,
7010,
18701,
1476,
2583,
15341,
11095,
203,
18701,
1135,
12,
6430,
13,
377,
288,
203,
3639,
327,
1674,
287,
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
]
|
./full_match/42220/0xD3b0E4928D4c8Ba7c3037d7F05E56DF8CC78b450/sources/out/ProtocolFeePercentagesProvider_flat.sol | * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that don't override one of these declarations./ Generalities about the Vault: - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning a boolean value: in these scenarios, a non-reverting call is assumed to be successful. - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g. while execution control is transferred to a token contract during a swap) will result in a revert. View functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results. Contracts calling view functions in the Vault must make sure the Vault has not already been entered. - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools. Authorizer Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller can perform a given action. Relayers Additionally, it is possible for an account to perform certain actions on behalf of another one, using their Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions, and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield this power, two things must occur: - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This means that Balancer governance must approve each individual contract to act as a relayer for the intended functions. - Each user must approve the relayer to act on their behalf. This double protection means users cannot be tricked into approving malicious relayers (because they will not have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised Authorizer or governance drain user funds, since they would also need to be approved by each individual user. Internal Balance Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users. Internal Balance management features batching, which means a single contract call can be used to perform multiple operations of different kinds, with different senders and recipients, at once. | interface IVault is ISignaturesValidator, ITemporarilyPausable, IAuthentication {
function getAuthorizer() external view returns (IAuthorizer);
function setAuthorizer(IAuthorizer newAuthorizer) external;
event AuthorizerChanged(IAuthorizer indexed newAuthorizer);
function hasApprovedRelayer(address user, address relayer) external view returns (bool);
function setRelayerApproval(
address sender,
address relayer,
bool approved
) external;
event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved);
function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory);
function manageUserBalance(UserBalanceOp[] memory ops) external payable;
without manual WETH wrapping or unwrapping.
}
struct UserBalanceOp {
UserBalanceOpKind kind;
IAsset asset;
uint256 amount;
address sender;
address payable recipient;
}
enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL }
event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta);
event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount);
enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN }
function registerPool(PoolSpecialization specialization) external returns (bytes32);
event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization);
function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);
function registerTokens(
bytes32 poolId,
IERC20[] memory tokens,
address[] memory assetManagers
) external;
event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers);
function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external;
event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens);
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
external
view
returns (
uint256 cash,
uint256 managed,
uint256 lastChangeBlock,
address assetManager
);
function getPoolTokens(bytes32 poolId)
external
view
returns (
IERC20[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
);
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable;
struct JoinPoolRequest {
IAsset[] assets;
uint256[] maxAmountsIn;
bytes userData;
bool fromInternalBalance;
}
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest memory request
) external;
struct ExitPoolRequest {
IAsset[] assets;
uint256[] minAmountsOut;
bytes userData;
bool toInternalBalance;
}
bytes32 indexed poolId,
address indexed liquidityProvider,
IERC20[] tokens,
int256[] deltas,
uint256[] protocolFeeAmounts
);
event PoolBalanceChanged(
enum PoolBalanceChangeKind { JOIN, EXIT }
enum SwapKind { GIVEN_IN, GIVEN_OUT }
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256);
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
IAsset assetIn;
IAsset assetOut;
uint256 amount;
bytes userData;
}
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
) external payable returns (int256[] memory);
struct BatchSwapStep {
bytes32 poolId;
uint256 assetInIndex;
uint256 assetOutIndex;
uint256 amount;
bytes userData;
}
bytes32 indexed poolId,
IERC20 indexed tokenIn,
IERC20 indexed tokenOut,
uint256 amountIn,
uint256 amountOut
);
event Swap(
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
function queryBatchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds
) external returns (int256[] memory assetDeltas);
function flashLoan(
IFlashLoanRecipient recipient,
IERC20[] memory tokens,
uint256[] memory amounts,
bytes memory userData
) external;
event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount);
function managePoolBalance(PoolBalanceOp[] memory ops) external;
struct PoolBalanceOp {
PoolBalanceOpKind kind;
bytes32 poolId;
IERC20 token;
uint256 amount;
}
bytes32 indexed poolId,
address indexed assetManager,
IERC20 indexed token,
int256 cashDelta,
int256 managedDelta
);
enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE }
event PoolBalanceManaged(
}
| 16,349,439 | [
1,
5080,
3903,
1560,
364,
326,
17329,
2922,
6835,
300,
1158,
3903,
578,
1071,
2590,
1005,
316,
326,
6835,
716,
2727,
1404,
3849,
1245,
434,
4259,
12312,
18,
19,
9544,
1961,
2973,
326,
17329,
30,
300,
3497,
4009,
502,
7323,
21368,
358,
296,
7860,
2187,
518,
23457,
21368,
358,
4232,
39,
3462,
17,
832,
18515,
1147,
20092,
18,
13899,
854,
906,
4193,
596,
434,
326,
17329,
635,
4440,
326,
1375,
45,
654,
39,
3462,
18,
13866,
68,
445,
16,
471,
906,
4193,
316,
635,
4440,
1375,
45,
654,
39,
3462,
18,
13866,
1265,
8338,
657,
4259,
6088,
16,
326,
5793,
1297,
1240,
7243,
2935,
326,
17329,
358,
999,
3675,
2430,
635,
4440,
1375,
45,
654,
39,
3462,
18,
12908,
537,
8338,
1021,
1338,
17585,
628,
326,
4232,
39,
3462,
4529,
716,
353,
3260,
353,
4186,
486,
5785,
279,
1250,
460,
30,
316,
4259,
22456,
16,
279,
1661,
17,
266,
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,
12003,
353,
467,
23918,
5126,
16,
467,
1837,
3831,
10243,
16507,
16665,
16,
467,
6492,
288,
203,
203,
203,
565,
445,
336,
17170,
1435,
3903,
1476,
1135,
261,
45,
17170,
1769,
203,
203,
565,
445,
444,
17170,
12,
45,
17170,
394,
17170,
13,
3903,
31,
203,
203,
565,
871,
25685,
5033,
12,
45,
17170,
8808,
394,
17170,
1769,
203,
203,
203,
565,
445,
711,
31639,
1971,
1773,
12,
2867,
729,
16,
1758,
1279,
1773,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
203,
565,
445,
444,
1971,
1773,
23461,
12,
203,
3639,
1758,
5793,
16,
203,
3639,
1758,
1279,
1773,
16,
203,
3639,
1426,
20412,
203,
565,
262,
3903,
31,
203,
203,
565,
871,
4275,
1773,
23461,
5033,
12,
2867,
8808,
1279,
1773,
16,
1758,
8808,
5793,
16,
1426,
20412,
1769,
203,
203,
203,
565,
445,
16918,
13937,
12,
2867,
729,
16,
467,
654,
39,
3462,
8526,
3778,
2430,
13,
3903,
1476,
1135,
261,
11890,
5034,
8526,
3778,
1769,
203,
203,
565,
445,
10680,
1299,
13937,
12,
1299,
13937,
3817,
8526,
3778,
6727,
13,
3903,
8843,
429,
31,
203,
203,
377,
2887,
11297,
678,
1584,
44,
14702,
578,
11014,
1382,
18,
203,
97,
203,
565,
1958,
2177,
13937,
3817,
288,
203,
3639,
2177,
13937,
3817,
5677,
3846,
31,
203,
3639,
467,
6672,
3310,
31,
203,
3639,
2254,
5034,
3844,
31,
203,
3639,
1758,
5793,
31,
203,
3639,
1758,
8843,
429,
8027,
31,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
565,
2792,
2177,
13937,
3817,
5677,
288,
2030,
28284,
67,
2
]
|
./full_match/1/0x190F44c7a5e06ad5A5fD5e17522Fe243B9a3cFeE/sources/src/MembershipManager.sol | @notice Sets the points for a given Ethereum address. @dev This function allows the contract owner to set the points for a specific Ethereum address. @param _tokenId The ID of the membership NFT. @param _loyaltyPoints The number of loyalty points to set for the specified NFT. @param _tierPoints The number of tier points to set for the specified NFT. | function setPoints(uint256 _tokenId, uint40 _loyaltyPoints, uint40 _tierPoints) external {
_requireAdmin();
_setPoints(_tokenId, _loyaltyPoints, _tierPoints);
_claimTier(_tokenId);
_emitNftUpdateEvent(_tokenId);
}
error InvalidWithdraw();
| 9,732,223 | [
1,
2785,
326,
3143,
364,
279,
864,
512,
18664,
379,
1758,
18,
225,
1220,
445,
5360,
326,
6835,
3410,
358,
444,
326,
3143,
364,
279,
2923,
512,
18664,
379,
1758,
18,
225,
389,
2316,
548,
1021,
1599,
434,
326,
12459,
423,
4464,
18,
225,
389,
2466,
15006,
5636,
1021,
1300,
434,
437,
93,
15006,
3143,
358,
444,
364,
326,
1269,
423,
4464,
18,
225,
389,
88,
2453,
5636,
1021,
1300,
434,
17742,
3143,
358,
444,
364,
326,
1269,
423,
4464,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
444,
5636,
12,
11890,
5034,
389,
2316,
548,
16,
2254,
7132,
389,
2466,
15006,
5636,
16,
2254,
7132,
389,
88,
2453,
5636,
13,
3903,
288,
203,
3639,
389,
6528,
4446,
5621,
203,
3639,
389,
542,
5636,
24899,
2316,
548,
16,
389,
2466,
15006,
5636,
16,
389,
88,
2453,
5636,
1769,
203,
3639,
389,
14784,
15671,
24899,
2316,
548,
1769,
203,
3639,
389,
18356,
50,
1222,
1891,
1133,
24899,
2316,
548,
1769,
203,
565,
289,
203,
203,
565,
555,
1962,
1190,
9446,
5621,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x89710b9B4076345BC89cfc6D5a0Bb10B73f15c7b/sources/contracts/interfaces/ICollateralLiquidator.sol | * @title Interface to a Collateral Liquidator/ | interface ICollateralLiquidator {
function name() external view returns (string memory);
function liquidate(
address currencyToken,
address collateralToken,
uint256 collateralTokenId,
bytes calldata collateralWrapperContext,
bytes calldata liquidationContext
) external;
pragma solidity ^0.8.0;
}
| 16,469,774 | [
1,
1358,
358,
279,
17596,
2045,
287,
511,
18988,
350,
639,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
467,
13535,
2045,
287,
48,
18988,
350,
639,
288,
203,
565,
445,
508,
1435,
3903,
1476,
1135,
261,
1080,
3778,
1769,
203,
203,
565,
445,
4501,
26595,
340,
12,
203,
3639,
1758,
5462,
1345,
16,
203,
3639,
1758,
4508,
2045,
287,
1345,
16,
203,
3639,
2254,
5034,
4508,
2045,
287,
1345,
548,
16,
203,
3639,
1731,
745,
892,
4508,
2045,
287,
3611,
1042,
16,
203,
3639,
1731,
745,
892,
4501,
26595,
367,
1042,
203,
565,
262,
3903,
31,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
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
]
|
./full_match/4/0x52fBf95b0174E656A67A6B18de4965fED58806A8/sources/Users/techstardust/Desktop/levels-michael/merged_contracts/LevelsVault.sol | Low level withdraw function | function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][from];
massUpdatePools();
if(_amount > 0) {
require(pool.withdrawable, "Withdrawing from this pool is disabled");
user.amount = user.amount.sub(_amount, "Insufficient balance");
if(_pid == 0) {
if(voidWithdrawList[to] || LevelsETHLPBurnAddress == address(0)) {
pool.token.transfer(address(to), _amount);
pool.token.transfer(address(to), _amount.mul(95).div(100));
pool.token.transfer(address(LevelsETHLPBurnAddress), _amount.mul(5).div(100));
}
pool.token.transfer(address(to), _amount);
}
}
user.rewardDebt = user.amount.mul(pool.accLevelsPerShare).div(1e12);
emit Withdraw(to, _pid, _amount);
if(_amount > 0) {
require(pool.withdrawable, "Withdrawing from this pool is disabled");
user.amount = user.amount.sub(_amount, "Insufficient balance");
if(_pid == 0) {
if(voidWithdrawList[to] || LevelsETHLPBurnAddress == address(0)) {
pool.token.transfer(address(to), _amount);
pool.token.transfer(address(to), _amount.mul(95).div(100));
pool.token.transfer(address(LevelsETHLPBurnAddress), _amount.mul(5).div(100));
}
pool.token.transfer(address(to), _amount);
}
}
user.rewardDebt = user.amount.mul(pool.accLevelsPerShare).div(1e12);
emit Withdraw(to, _pid, _amount);
if(_amount > 0) {
require(pool.withdrawable, "Withdrawing from this pool is disabled");
user.amount = user.amount.sub(_amount, "Insufficient balance");
if(_pid == 0) {
if(voidWithdrawList[to] || LevelsETHLPBurnAddress == address(0)) {
pool.token.transfer(address(to), _amount);
pool.token.transfer(address(to), _amount.mul(95).div(100));
pool.token.transfer(address(LevelsETHLPBurnAddress), _amount.mul(5).div(100));
}
pool.token.transfer(address(to), _amount);
}
}
user.rewardDebt = user.amount.mul(pool.accLevelsPerShare).div(1e12);
emit Withdraw(to, _pid, _amount);
} else {
} else {
}
| 12,379,735 | [
1,
10520,
1801,
598,
9446,
445,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
1918,
9446,
12,
11890,
5034,
389,
6610,
16,
2254,
5034,
389,
8949,
16,
1758,
628,
16,
1758,
358,
13,
2713,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
2080,
15533,
203,
203,
3639,
8039,
1891,
16639,
5621,
203,
203,
203,
3639,
309,
24899,
8949,
405,
374,
13,
288,
203,
5411,
2583,
12,
6011,
18,
1918,
9446,
429,
16,
315,
1190,
9446,
310,
628,
333,
2845,
353,
5673,
8863,
203,
5411,
729,
18,
8949,
273,
729,
18,
8949,
18,
1717,
24899,
8949,
16,
315,
5048,
11339,
11013,
8863,
203,
5411,
309,
24899,
6610,
422,
374,
13,
288,
203,
7734,
309,
12,
6459,
1190,
9446,
682,
63,
869,
65,
747,
4557,
87,
1584,
44,
14461,
38,
321,
1887,
422,
1758,
12,
20,
3719,
288,
203,
10792,
2845,
18,
2316,
18,
13866,
12,
2867,
12,
869,
3631,
389,
8949,
1769,
203,
10792,
2845,
18,
2316,
18,
13866,
12,
2867,
12,
869,
3631,
389,
8949,
18,
16411,
12,
8778,
2934,
2892,
12,
6625,
10019,
203,
10792,
2845,
18,
2316,
18,
13866,
12,
2867,
12,
12240,
1584,
44,
14461,
38,
321,
1887,
3631,
389,
8949,
18,
16411,
12,
25,
2934,
2892,
12,
6625,
10019,
203,
7734,
289,
203,
7734,
2845,
18,
2316,
18,
13866,
12,
2867,
12,
869,
3631,
389,
8949,
1769,
203,
5411,
289,
203,
3639,
289,
203,
3639,
729,
18,
266,
2913,
758,
23602,
273,
729,
18,
8949,
18,
16411,
12,
6011,
18,
8981,
12240,
2173,
9535,
2
]
|
pragma solidity ^0.4.23;
import "../common/SignUtils.sol";
import "./ERC725.sol";
import "./ClaimableIdentity.sol";
/**
* @title Self sovereign Identity
* @author Ricardo Guilherme Schmidt (Status Research & Development GmbH)
*/
contract Identity is ClaimableIdentity, ERC725 {
uint256 public nonce; //not approved transactions reserve nonce
address public recovery; //if defined can change salt and add a new key
uint256 salt; //used for disabling all authorizations at once
uint256 threshold;
mapping (bytes32 => Key) keys; //used for quering by other contracts
mapping (bytes32 => bool) isKeyPurpose; //used for authorization
mapping (bytes32 => bytes32[]) keysByPurpose; //used for listing
/// @dev Fallback function accepts Ether transactions.
/// @dev Fallback function accepts Ether transactions.
function ()
external
payable
{}
/**
* @notice constructor builds identity with provided `_keys`
* or uses `msg.sender` as first MANAGEMENT + ACTION key
* @param _keys Keys to add
* @param _purposes `_keys` corresponding purposes
* @param _types `_keys` corresponding types
* @param _managerThreshold how much keys needs to sign management calls
* @param _actorThreshold how much keys need to sign action management calls
* @param _recoveryContract Option to initialize with recovery defined
*/
constructor(
bytes32[] _keys,
uint256 _threshold,
address _recoveryContract
) public {
constructIdentity(
_keys,
_threshold,
_recoveryContract
);
}
/**
* @dev initialize identity
* @param _keys array of keys, length need to be greater than zero
* @param _purposes array of keys's purposes, length need == keys length
* @param _types array of key's types, length need == keys length
* @param _managerThreshold how much managers need to approve self call, need to be at least managers added
* @param _actorThreshold how much actors need to approve external call
* @param _recoveryContract optionally initialize with recovery contract
*/
function constructIdentity(
bytes32[] _keys,
uint256 _threshold,
address _recoveryContract
)
internal
{
uint256 _salt = salt;
uint len = _keys.length;
require(len > 0);
uint managersAdded = 0;
for(uint i = 0; i < len; i++) {
uint256 _purpose = _purposes[i];
storeKey(_keys[i], _purpose, _types[i], _salt);
if(_purpose == MANAGEMENT_KEY) {
managersAdded++;
}
}
require(_managerThreshold <= managersAdded, "managers added is less then required");
purposeThreshold[MANAGEMENT_KEY] = _managerThreshold;
purposeThreshold[ACTION_KEY] = _actorThreshold;
recovery = _recoveryContract;
}
/// @dev Allows to add a new owner to the Safe and update the threshold at the same time.
/// This can only be done via a Safe transaction.
/// @param owner New owner address.
/// @param _threshold New threshold.
function addKey(bytes32 _key, uint256 _purpose, uint256 _keyType)
public
returns (bool success)
{
// Owner address cannot be null.
require(_key != 0);
// No duplicate owners allowed.
require(_keys[owner]);
owners.push(owner);
isOwner[owner] = true;
// Change threshold if threshold was changed.
if (threshold != _threshold)
changeThreshold(_threshold);
}
/// @dev Allows to remove an owner from the Safe and update the threshold at the same time.
/// This can only be done via a Safe transaction.
/// @param ownerIndex Array index position of owner address to be removed.
/// @param owner Owner address to be removed.
/// @param _threshold New threshold.
function removeOwner(uint256 ownerIndex, address owner, uint8 _threshold)
public
onlyWallet
{
// Only allow to remove an owner, if threshold can still be reached.
require(owners.length - 1 >= _threshold);
// Validate owner address corresponds to owner index.
require(owners[ownerIndex] == owner);
isOwner[owner] = false;
owners[ownerIndex] = owners[owners.length - 1];
owners.length--;
// Change threshold if threshold was changed.
if (threshold != _threshold)
changeThreshold(_threshold);
}
/**
* @dev store a new key or push purpose of already exists
* @param _salt current salt
* @return true if success
*/
function storeKey(
bytes32 _key,
uint256 _purpose,
uint256 _type,
uint256 _salt
)
private
returns(bool success)
{
require(_key != 0);
require(_purpose != 0);
require(!keys[_keys]); //cannot add a key already added
uint256[] memory purposes = new uint256[](1); //create new array with first purpose
purposes[0] = _purpose;
keys[_keys] = Key(_purpose,_type,_key); //add new key
emit KeyAdded(_key, _purpose, _type);
return true;
}
/*
/// @dev Allows to execute a Safe transaction confirmed by required number of owners.
/// @param to Destination address of Safe transaction.
/// @param value Ether value of Safe transaction.
/// @param data Data payload of Safe transaction.
/// @param operation Operation type of Safe transaction.
/// @param v Array of signature V values sorted by owner addresses.
/// @param r Array of signature R values sorted by owner addresses.
/// @param s Array of signature S values sorted by owner addresses.
/// @param _owners List of Safe owners confirming via regular transactions sorted by owner addresses.
/// @param indices List of indeces of Safe owners confirming via regular transactions.
function execute(address to, uint256 value, bytes data, Operation operation, uint8[] v, bytes32[] r, bytes32[] s, address[] _owners, uint256[] indices)
public
{
bytes32 transactionHash = getTransactionHash(to, value, data, operation, nonce);
// There cannot be an owner with address 0.
address lastOwner = address(0);
address currentOwner;
uint256 i;
uint256 j = 0;
// Validate threshold is reached.
for (i = 0; i < threshold; i++) {
// Check confirmations done with regular transactions or by msg.sender.
if (indices.length > j && i == indices[j]) {
require(msg.sender == _owners[j] || isConfirmed[_owners[j]][transactionHash]);
currentOwner = _owners[j];
j += 1;
}
// Check confirmations done with signed messages.
else
currentOwner = ecrecover(transactionHash, v[i-j], r[i-j], s[i-j]);
require(isOwner[currentOwner]);
require(currentOwner > lastOwner);
lastOwner = currentOwner;
}
// Delete storage to receive refunds.
if (_owners.length > 0) {
for (i = 0; i < _owners.length; i++) {
if (msg.sender != _owners[i])
isConfirmed[_owners[i]][transactionHash] = false;
}
}
// Increase nonce and execute transaction.
nonce += 1;
execute(to, value, data, operation);
}
function execute(address to, uint256 value, bytes data, Operation operation)
internal
{
if (operation == Operation.Call)
require(executeCall(to, value, data));
else if (operation == Operation.DelegateCall)
require(executeDelegateCall(to, data));
else {
address newContract = executeCreate(data);
require(newContract != 0);
ContractCreation(newContract);
}
}
function executeCall(address to, uint256 value, bytes data)
internal
returns (bool success)
{
assembly {
success := call(not(0), to, value, add(data, 0x20), mload(data), 0, 0)
}
}
function executeDelegateCall(address to, bytes data)
internal
returns (bool success)
{
assembly {
success := delegatecall(not(0), to, add(data, 0x20), mload(data), 0, 0)
}
}
function executeCreate(bytes data)
internal
returns (address newContract)
{
assembly {
newContract := create(0, add(data, 0x20), mload(data))
}
}
*/
}
| if defined can change salt and add a new key
| address public recovery; | 989,756 | [
1,
430,
2553,
848,
2549,
4286,
471,
527,
279,
394,
498,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1758,
1071,
11044,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/3/0x54d5d508a5EddDAD52Db7667646FdCEF819dF757/sources/dh.sol | * @dev Safely transfers the ownership of a given token ID to another address If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer, and return the magic value `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, the transfer is reverted. Requires the _msgSender() to be the owner, approved, or operator @param from current owner of the token @param to address to receive the ownership of the given token ID @param tokenId uint256 ID of the token to be transferred @param _data bytes data to send along with a safe transfer check/ | function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override Paused{
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
| 14,163,614 | [
1,
26946,
2357,
29375,
326,
23178,
434,
279,
864,
1147,
1599,
358,
4042,
1758,
971,
326,
1018,
1758,
353,
279,
6835,
16,
518,
1297,
2348,
288,
45,
654,
39,
27,
5340,
12952,
17,
265,
654,
39,
27,
5340,
8872,
5779,
1492,
353,
2566,
12318,
279,
4183,
7412,
16,
471,
327,
326,
8146,
460,
1375,
3890,
24,
12,
79,
24410,
581,
5034,
2932,
265,
654,
39,
27,
5340,
8872,
12,
2867,
16,
2867,
16,
11890,
5034,
16,
3890,
2225,
3719,
68,
31,
3541,
16,
326,
7412,
353,
15226,
329,
18,
16412,
326,
389,
3576,
12021,
1435,
358,
506,
326,
3410,
16,
20412,
16,
578,
3726,
225,
628,
783,
3410,
434,
326,
1147,
225,
358,
1758,
358,
6798,
326,
23178,
434,
326,
864,
1147,
1599,
225,
1147,
548,
2254,
5034,
1599,
434,
326,
1147,
358,
506,
906,
4193,
225,
389,
892,
1731,
501,
358,
1366,
7563,
598,
279,
4183,
7412,
866,
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,
445,
4183,
5912,
1265,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
1147,
548,
16,
1731,
3778,
389,
892,
13,
1071,
5024,
3849,
21800,
3668,
95,
203,
3639,
2583,
24899,
291,
31639,
1162,
5541,
24899,
3576,
12021,
9334,
1147,
548,
3631,
315,
654,
39,
27,
5340,
30,
7412,
4894,
353,
486,
3410,
12517,
20412,
8863,
203,
3639,
389,
4626,
5912,
12,
2080,
16,
358,
16,
1147,
548,
16,
389,
892,
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
]
|
./full_match/43113/0x79e6aaCD8986c9797B3f8AfbeAE04130Da184Cd4/sources/contracts/Oracle.sol | voter must have votes to allocate can only vote if there is a proposal voter must not have voted on this proposal this prevents this account from voting again on this data proposal (see above) votes are simply one's entire token balance deposited in this oracle contract | function vote(bool _sendData) external {
require(adminStruct[msg.sender].tokens > 0);
require(params[1] != 0);
require(adminStruct[msg.sender].voteTracker != params[2]);
adminStruct[msg.sender].voteTracker = params[2];
if (_sendData) {
params[5] += adminStruct[msg.sender].tokens;
params[6] += adminStruct[msg.sender].tokens;
}
}
| 7,168,380 | [
1,
90,
20005,
1297,
1240,
19588,
358,
10101,
848,
1338,
12501,
309,
1915,
353,
279,
14708,
331,
20005,
1297,
486,
1240,
331,
16474,
603,
333,
14708,
333,
17793,
333,
2236,
628,
331,
17128,
3382,
603,
333,
501,
14708,
261,
5946,
5721,
13,
19588,
854,
8616,
1245,
1807,
7278,
1147,
11013,
443,
1724,
329,
316,
333,
20865,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
12501,
12,
6430,
389,
4661,
751,
13,
3903,
288,
203,
3639,
2583,
12,
3666,
3823,
63,
3576,
18,
15330,
8009,
7860,
405,
374,
1769,
203,
3639,
2583,
12,
2010,
63,
21,
65,
480,
374,
1769,
203,
3639,
2583,
12,
3666,
3823,
63,
3576,
18,
15330,
8009,
25911,
8135,
480,
859,
63,
22,
19226,
203,
3639,
3981,
3823,
63,
3576,
18,
15330,
8009,
25911,
8135,
273,
859,
63,
22,
15533,
203,
3639,
309,
261,
67,
4661,
751,
13,
288,
203,
5411,
859,
63,
25,
65,
1011,
3981,
3823,
63,
3576,
18,
15330,
8009,
7860,
31,
203,
5411,
859,
63,
26,
65,
1011,
3981,
3823,
63,
3576,
18,
15330,
8009,
7860,
31,
203,
3639,
289,
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
]
|
pragma solidity ^0.4.24;
import { QuestionsLib } from "./QuestionsLib.sol";
import { HSKALib } from "./HSKALib.sol";
import { Utils } from "./Utils.sol";
import { strings } from "./strings.sol";
contract Evaluation {
using strings for *;
mapping(address => mapping(uint => EvaluatedCourse)) public studentEvaluations;
mapping(address => mapping(uint => bool)) public studentCourseRegistrations;
mapping(uint => Course) public registeredCourses;
address public owner;
uint public coursesCount;
uint public evalInitTimestamp;
uint public evalStartTimestamp;
uint public evalEndTimestamp;
string public semester;
uint public testNow; //Demo only
struct Course {
uint id;
HSKALib.Courses courseKey;
HSKALib.Lecturers lecturerKey;
uint numberOfQuestions;
uint numberOfRegistrations;
uint numberOfEvaluations;
bool hasNumerical;
bool hasTextual;
mapping(uint => QuestionsLib.QuestionArchetype) questionsToEvaluate;
mapping(uint => address) accountRegistrations;
mapping(uint => address) accountEvaluations;
}
struct EvaluatedCourse {
uint courseId;
bool isEvaluated;
mapping(uint => uint) answersToUIntQuestions;
mapping(uint => string) answersToTxtQuestions;
}
modifier onlyAdmin() {
require(msg.sender == owner, "Not an owner");
_;
}
modifier inRegistrationInterval() {
require(testNow < evalStartTimestamp && testNow >= evalInitTimestamp, "Registration time interval is expired");
_;
}
modifier inEvaluationInterval() {
require(testNow <= evalEndTimestamp && testNow >= evalStartTimestamp, "Not in evaluation time interval");
_;
}
modifier afterEvaluationInterval() {
require(testNow >= evalEndTimestamp, "Not in post-evaluation interval");
_;
}
event evaluatedEvent(
uint indexed _courseId
);
constructor(string _semester, uint startOffsetInDays, uint _durationInDays) public {
owner = msg.sender;
semester = _semester;
evalInitTimestamp = now;
testNow = now;
evalStartTimestamp = now + startOffsetInDays * 1 days;
evalEndTimestamp = evalStartTimestamp + (_durationInDays * 1 days);
//Register courses and assign questions
registerCourseForEvaluation(HSKALib.Courses.course1, HSKALib.Lecturers.prof1);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q1);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q2);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q3);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q11);
registerCourseForEvaluation(HSKALib.Courses.course2, HSKALib.Lecturers.prof1);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q3);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q10);
registerCourseForEvaluation(HSKALib.Courses.course3, HSKALib.Lecturers.prof2);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q4);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q8);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q7);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q5);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q6);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q11);
registerCourseForEvaluation(HSKALib.Courses.course4, HSKALib.Lecturers.prof3);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q4);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q5);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q8);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q9);
}
function registerCourseForEvaluation(HSKALib.Courses _courseKey, HSKALib.Lecturers _lecturerKey)
private inRegistrationInterval returns(bool) {
coursesCount++;
registeredCourses[coursesCount] = Course({
id: coursesCount,
courseKey: _courseKey,
lecturerKey: _lecturerKey,
numberOfQuestions: 0,
numberOfRegistrations: 0,
numberOfEvaluations: 0,
hasNumerical: false,
hasTextual: false
});
return true;
}
function assignQuestionToCourse(uint _courseId, QuestionsLib.QuestionArchetype _qarch)
private inRegistrationInterval returns(bool) {
Course storage _course = registeredCourses[_courseId];
_course.questionsToEvaluate[_course.numberOfQuestions] = _qarch;
_course.numberOfQuestions++;
if (QuestionsLib.isTextTypedInput(_qarch))
_course.hasTextual = true;
else
_course.hasNumerical = true;
return true;
}
// @param _courseId: course id to be evaluated
// @param _uintAns: all answers for non-txt questions(for frontend: should be ordered)
// @param _txtAnswers: all answers for txt-questions, delimetered by '//'
function evaluateCourse(uint _courseId, uint[] _uintAns, string _txtAnswers)
public inEvaluationInterval returns(bool) {
require(studentCourseRegistrations[msg.sender][_courseId], "Not registered for this course");
require(!studentEvaluations[msg.sender][_courseId].isEvaluated, "This course is already evaluated");
uint uintAmount = getNumberOfUINTQuestions(_courseId);
require(_uintAns.length == uintAmount, "The evaluation for this course is not complete");
var s = _txtAnswers.toSlice();
var delim = "//".toSlice();
uint currentUintCnt = 0;
for (uint i = 0; i < registeredCourses[_courseId].numberOfQuestions; i++) {
if (!QuestionsLib.isTextTypedInput(registeredCourses[_courseId].questionsToEvaluate[i])) {
require(_uintAns[currentUintCnt] > 0 &&
_uintAns[currentUintCnt] <= QuestionsLib.getMaxVal(registeredCourses[_courseId].questionsToEvaluate[i]),
"Incorrect answer");
studentEvaluations[msg.sender][_courseId].answersToUIntQuestions[i] = _uintAns[currentUintCnt];
currentUintCnt++;
} else {
var currentStr = s.split(delim).toString();
require(currentStr.toSlice().len() <= 128, "The answer exceeded 128 characters!");
studentEvaluations[msg.sender][_courseId].answersToTxtQuestions[i] = currentStr;
}
}
studentEvaluations[msg.sender][_courseId].isEvaluated = true;
registeredCourses[_courseId]
.accountEvaluations[++registeredCourses[_courseId].numberOfEvaluations] = msg.sender;
emit evaluatedEvent(_courseId);
return true;
}
// @param _account: account to be registered
// @param _courseId: course to be assigned
function registerAccountForCourseEval(address _account, uint _courseId)
payable public inRegistrationInterval onlyAdmin {
require(!studentCourseRegistrations[_account][_courseId],
"Student is already registered");
require(registeredCourses[_courseId].id != 0,
"The course is not registered");
_account.transfer(msg.value);
studentCourseRegistrations[_account][_courseId] = true;
registeredCourses[_courseId]
.accountRegistrations[++registeredCourses[_courseId].numberOfRegistrations] = _account;
}
function getCourseTitle(uint _cId) public view returns(string) {
return HSKALib.getCourseName(registeredCourses[_cId].courseKey);
}
function getCourseLecturerName(uint _cId) public view returns(string) {
return HSKALib.getLecturerName(registeredCourses[_cId].lecturerKey);
}
function getQuestionBodyByCourse(uint _cId, uint _qId) public view returns(string) {
return QuestionsLib.getQuestionBody(registeredCourses[_cId].questionsToEvaluate[_qId]);
}
// @param _account: account to read evaluation from
// @param _courseId: course id to read evaluation from
// @param _qId: question id to read evaluation from
// @returns string: answer
// @returns bool: true, if the answer is non-textual (numerical)
function readEvaluation(address _account, uint _courseId, uint _qId)
public view returns(string, bool) {
if (isTextualQuestion(_courseId, _qId))
return (studentEvaluations[_account][_courseId].answersToTxtQuestions[_qId], false);
return (Utils.uintToString(studentEvaluations[_account][_courseId].answersToUIntQuestions[_qId]), true);
}
function isTextualQuestion(uint _courseId, uint _qId) public view returns(bool) {
return QuestionsLib.isTextTypedInput(
registeredCourses[_courseId].questionsToEvaluate[_qId]);
}
function isCourseEvaluatedByAccount(address _account, uint _courseId) public view returns(bool) {
return studentEvaluations[_account][_courseId].isEvaluated;
}
function getNumberOfUINTQuestions(uint _courseId) public view returns(uint _counter) {
for (uint i = 0; i < registeredCourses[_courseId].numberOfQuestions; i++) {
if (!QuestionsLib.isTextTypedInput(registeredCourses[_courseId].questionsToEvaluate[i]))
_counter++;
}
}
function checkRegistration(address _adr, uint _courseId) public view returns(bool) {
return studentCourseRegistrations[_adr][_courseId];
}
function increaseNowTime(uint timeInDays) onlyAdmin public {
testNow += timeInDays * 1 days;
}
function decreaseNowTime(uint timeInDays) onlyAdmin public {
testNow -= timeInDays * 1 days;
}
function destroy() public onlyAdmin {
selfdestruct(owner); // send funds to organizers
}
function contributeToContract() public payable {}
function getContractBalance() public view returns(uint) {
return address(this).balance;
}
function getAvailableCourses(address _adr) public view returns(uint[]) {
uint[] _resArr;
for (uint i = 1; i <= coursesCount; i++)
if (studentCourseRegistrations[_adr][i] == true)
_resArr.push(i);
return _resArr;
}
function getRegAccountsByCourse(uint _courseId) public view returns(address[]) {
address[] _adresses;
for (uint i = 1; i <= registeredCourses[_courseId].numberOfRegistrations; i++)
_adresses.push(registeredCourses[_courseId].accountRegistrations[i]);
return _adresses;
}
function getEvalAccountsByCourse(uint _courseId) public view returns(address[]) {
address[] _adresses;
for (uint i = 1; i <= registeredCourses[_courseId].numberOfEvaluations; i++)
_adresses.push(registeredCourses[_courseId].accountEvaluations[i]);
return _adresses;
}
function getMaxAnswerForQuestionWrapper(uint _cId, uint _qId) public view returns(uint) {
return QuestionsLib.getMaxVal(registeredCourses[_cId].questionsToEvaluate[_qId]);
}
function getRatingTextForValWrapper(uint _cId, uint _qId, uint _ansId) public view returns(string) {
return QuestionsLib.getRatingTextForVal(registeredCourses[_cId].questionsToEvaluate[_qId], _ansId);
}
} | Register courses and assign questions | constructor(string _semester, uint startOffsetInDays, uint _durationInDays) public {
owner = msg.sender;
semester = _semester;
evalInitTimestamp = now;
testNow = now;
evalStartTimestamp = now + startOffsetInDays * 1 days;
evalEndTimestamp = evalStartTimestamp + (_durationInDays * 1 days);
registerCourseForEvaluation(HSKALib.Courses.course1, HSKALib.Lecturers.prof1);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q1);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q2);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q3);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q11);
registerCourseForEvaluation(HSKALib.Courses.course2, HSKALib.Lecturers.prof1);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q3);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q10);
registerCourseForEvaluation(HSKALib.Courses.course3, HSKALib.Lecturers.prof2);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q4);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q8);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q7);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q5);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q6);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q11);
registerCourseForEvaluation(HSKALib.Courses.course4, HSKALib.Lecturers.prof3);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q4);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q5);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q8);
assignQuestionToCourse(coursesCount, QuestionsLib.QuestionArchetype.q9);
}
| 904,810 | [
1,
3996,
17224,
471,
2683,
13494,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3885,
12,
1080,
389,
12000,
7654,
16,
2254,
18245,
382,
9384,
16,
2254,
389,
8760,
382,
9384,
13,
1071,
288,
203,
3639,
3410,
273,
1234,
18,
15330,
31,
203,
3639,
6111,
7654,
273,
389,
12000,
7654,
31,
203,
3639,
5302,
2570,
4921,
273,
2037,
31,
203,
3639,
1842,
8674,
273,
2037,
31,
203,
3639,
5302,
1685,
4921,
273,
2037,
397,
18245,
382,
9384,
380,
404,
4681,
31,
203,
3639,
5302,
1638,
4921,
273,
5302,
1685,
4921,
397,
261,
67,
8760,
382,
9384,
380,
404,
4681,
1769,
203,
203,
3639,
1744,
39,
3117,
1290,
13468,
12,
44,
11129,
1013,
495,
18,
39,
10692,
18,
5566,
21,
16,
670,
11129,
1013,
495,
18,
48,
386,
295,
414,
18,
16121,
21,
1769,
203,
3639,
2683,
11665,
774,
39,
3117,
12,
15804,
1380,
16,
4783,
395,
1115,
5664,
18,
11665,
12269,
5872,
18,
85,
21,
1769,
203,
3639,
2683,
11665,
774,
39,
3117,
12,
15804,
1380,
16,
4783,
395,
1115,
5664,
18,
11665,
12269,
5872,
18,
85,
22,
1769,
203,
3639,
2683,
11665,
774,
39,
3117,
12,
15804,
1380,
16,
4783,
395,
1115,
5664,
18,
11665,
12269,
5872,
18,
85,
23,
1769,
203,
3639,
2683,
11665,
774,
39,
3117,
12,
15804,
1380,
16,
4783,
395,
1115,
5664,
18,
11665,
12269,
5872,
18,
85,
2499,
1769,
203,
203,
3639,
1744,
39,
3117,
1290,
13468,
12,
44,
11129,
1013,
495,
18,
39,
10692,
18,
5566,
22,
16,
670,
11129,
1013,
495,
18,
48,
386,
295,
414,
18,
16121,
21,
1769,
203,
3639,
2683,
11665,
774,
39,
3117,
12,
15804,
2
]
|
pragma solidity ^0.4.25;
/// @title FileFactory
/// @notice Facilitates the creation and deployment of files
/// @dev Factory contract to deploy individual files uploaded by users
contract FileFactory {
/// @notice Stores the list of files deployed by an address
mapping(address => address[]) uploadedFiles;
/// @notice Stores the list of files shared by an address
mapping(address => address[]) sharedFiles;
/// @notice Stores the list of files shared with an address
mapping(address => address[]) recipientFiles;
/// @notice Stores the list of files archived by all users
address[] archivedFiles;
/// @notice List of Uploaders
mapping(address => bool) uploaders;
/// @notice List of Recipients
mapping(address => bool) recipients;
/// @dev To restrict execution of certain functions to the uploaders
modifier isUploader(address _from) {
require(uploaders[_from], "Sender is not the uploader");
_;
}
/// @notice Deploys a file contract to the blockchain
/// @dev Deploys a new contract which stores file details
/// @param _digest Hash function digest
/// @param _hashFunction Hash function code
/// @param _size Size of _digest in bytes
/// @param _fileHash sha3 hash of the uploaded file
function createFile(bytes32 _digest, uint8 _hashFunction, uint8 _size, bytes32 _fileHash) public {
address newFile = new File(_digest, _hashFunction, _size, _fileHash, this, msg.sender);
uploadedFiles[msg.sender].push(newFile);
uploaders[msg.sender] = true;
}
/// @notice Retrives the list of deployed files
/// @dev Retrives the list of files from mapping uploadedFiles based on msg.sender
/// @return An address array with deployed files
function getUploadedFiles() public view returns(address[]) {
return uploadedFiles[msg.sender];
}
/// @notice Shares a deployed file with a recipient
/// @dev Updates the sharedFiles, recipientFiles and recipients with passed data
/// @param _recipient The address of recipient the file is to be shared with
/// @param _file The address of the deployed file
/// @param _from The address of the uploader
function shareFile(address _recipient, address _file, address _from) public isUploader(_from){
sharedFiles[_from].push(_file);
recipientFiles[_recipient].push(_file);
recipients[_recipient] = true;
}
/// @notice Retrives the list of files shared with a particular recipient
/// @dev Retrives the array from mapping recipientFiles based on msg.sender
/// @return An address array with files shared with the user.
function getRecipientFiles() public view returns(address[]) {
return recipientFiles[msg.sender];
}
/// @notice Retrives the list of files shared by a particular user
/// @dev Retrives the array from mapping sharedFiles based on msg.sender
/// @return An address array with shared files
function getSharedFiles() public view returns(address[]) {
return sharedFiles[msg.sender];
}
/// @notice Stores the file's address archived by any user
/// @dev Adds the archieved file address to archivedFiles array
/// @param _file The address of the deployed file to be archived
/// @param _from the address of the uploader
function archiveFile(address _file, address _from) public isUploader(_from){
archivedFiles.push(_file);
}
/// @notice Retrives the list of archived files
/// @dev Retrives the array archivedFiles
/// @return The array archivedFiles
function getArchivedFiles() public view returns(address[]) {
return archivedFiles;
}
/// @notice Restores the previously archived file
/// @dev Deletes the specified entry from archiveFile array
/// @param _index The index of the file in archiveFile array
/// @param _from The address of the uploader
function restoreFile(uint _index, address _from) public isUploader(_from) {
removeByIndex(_index, archivedFiles);
}
/// @notice Unshare a previously shared file with a specific user
/// @dev Removes the file's address from sharedFiles and recipientFiles
/// @param _indexOwner The index of file in sharedFiles
/// @param _indexRecipient The index of file in recipientFiles
/// @param _recipient The address of recipient
/// @param _from the Address of uploader
function stopSharing(uint _indexOwner, uint _indexRecipient, address _recipient, address _from) public isUploader(_from) {
removeByIndex(_indexOwner, sharedFiles[_from]);
removeByIndex(_indexRecipient, recipientFiles[_recipient]);
}
/// @dev Function to delete element from an array
/// @param _index The index of element to be removed
/// @param _array The array containing the element
function removeByIndex(uint _index, address[] storage _array) internal {
_array[_index] = _array[_array.length - 1];
delete _array[_array.length - 1];
_array.length--;
}
}
/// @title File
/// @notice Stores the details of a deployed file
/// @dev The file contract deployed by factory for each uploaded file
contract File {
/// @notice The address of the uploader
address public manager;
/// @notice sha3 hash of the file
bytes32 sha3hash;
struct Multihash {
bytes32 digest;
uint8 hashFunction;
uint8 size;
}
/// @notice The address of the factory contract
FileFactory ff;
/// @notice The IPFS hash of the file
Multihash fileIpfsHash;
/// @notice List of recipients the file is shared with
address[] recipientsList;
/// @notice Stores the encrypted key's IPFS hash for each recipient
mapping(address => Multihash) keyLocation;
/// @dev To restrict execution of certain function to the owner of the file
modifier isOwner() {
require(msg.sender == manager, "Sender is not the owner");
_;
}
/// @notice Initializes the variables with values passed by the factory upon file creation
/// @dev The constructor calles upon file deployment
/// @param _digest Hash function digest
/// @param _hashFunction Hash function code
/// @param _size size of _digest in bytes
/// @param _fileHash sha3 hash of the file
/// @param _factory The address of the factory contract
/// @param _creator The address of the uploader
constructor(bytes32 _digest, uint8 _hashFunction, uint8 _size, bytes32 _fileHash, address _factory, address _creator) public {
fileIpfsHash = Multihash(_digest, _hashFunction, _size);
manager = _creator;
sha3hash = _fileHash;
ff = FileFactory(_factory);
}
/// @notice Returns the file's IPFS hash
/// @dev Returns the IPFS hash of the uploaded file in multihash format
/// @return The IPFS hash's digest, hashFunction and size
function getFileDetail() public view returns (bytes32, uint8, uint8){
return (fileIpfsHash.digest, fileIpfsHash.hashFunction, fileIpfsHash.size);
}
/// @notice Returns the file's sha3 hash
/// @dev Returns the file's sha3 hash
/// @return The sha3 hash of the uploaded file
function getFileSha3Hash() public view returns (bytes32) {
return sha3hash;
}
/// @notice Function to share an uploaded file
/// @dev Updates the recipientsList and keyLocation and calls the factory' shareFile()
/// @param _recipient The address of the recipient
/// @param _digest Hash function digest of the key
/// @param _hashFunction Hash function code
/// @param _size size of _digest in bytes
function shareFile(address _recipient, bytes32 _digest, uint8 _hashFunction, uint8 _size) public isOwner {
recipientsList.push(_recipient);
keyLocation[_recipient] = Multihash(_digest, _hashFunction, _size);
ff.shareFile(_recipient, this, msg.sender);
}
/// @notice Retrives the details of a shared file
/// @dev Returns the file and it's key specific to the recipient
/// @return The file IPFS hash and it's key IPFS hash
function getSharedFileDetail() public view returns (bytes32 , uint8 , uint8 , bytes32 , uint8 , uint8 ){
return (fileIpfsHash.digest, fileIpfsHash.hashFunction, fileIpfsHash.size, keyLocation[msg.sender].digest, keyLocation[msg.sender].hashFunction, keyLocation[msg.sender].size);
}
/// @notice Function to archive the file
/// @dev Calls the factory's archiveFile()
function archiveFile() public isOwner {
ff.archiveFile(this, msg.sender);
}
/// @notice Function to restore the file
/// @dev Calls the factory's restoreFile()
/// @param _index The index of the file in the archiveFiles array
function restoreFile(uint _index) public isOwner {
ff.restoreFile(_index, msg.sender);
}
/// @notice Retrives the list of recipient for a given file
/// @dev Returns the list of recipients
/// @return The recipientsList array
function getRecipientsList() public view returns(address[]) {
return recipientsList;
}
/// @notice Function to stop sharing a file
/// @dev Deletes the data from keyLocation and recipientsList and calls the factory's stopSharing()
/// @param _indexFactoryOwner The file's index in sharedFiles array for the respective uploader
/// @param _indexFactoryRecipient The file's index in recipientFiles array for the respective recipient
/// @param _indexFileRecipient The recipient's index in recipientsList array
/// @param _recipient The array of the recipient
function stopSharing(uint _indexFactoryOwner, uint _indexFactoryRecipient, uint _indexFileRecipient, address _recipient) public isOwner {
delete keyLocation[_recipient];
recipientsList[_indexFileRecipient] = recipientsList[recipientsList.length - 1];
delete recipientsList[recipientsList.length - 1];
recipientsList.length--;
ff.stopSharing(_indexFactoryOwner, _indexFactoryRecipient, _recipient, msg.sender);
}
}
| @notice Initializes the variables with values passed by the factory upon file creation @dev The constructor calles upon file deployment @param _digest Hash function digest @param _hashFunction Hash function code @param _size size of _digest in bytes @param _fileHash sha3 hash of the file @param _factory The address of the factory contract @param _creator The address of the uploader | constructor(bytes32 _digest, uint8 _hashFunction, uint8 _size, bytes32 _fileHash, address _factory, address _creator) public {
fileIpfsHash = Multihash(_digest, _hashFunction, _size);
manager = _creator;
sha3hash = _fileHash;
ff = FileFactory(_factory);
}
| 7,278,956 | [
1,
9685,
326,
3152,
598,
924,
2275,
635,
326,
3272,
12318,
585,
6710,
225,
1021,
3885,
745,
281,
12318,
585,
6314,
225,
389,
10171,
2474,
445,
5403,
225,
389,
2816,
2083,
2474,
445,
981,
225,
389,
1467,
963,
434,
389,
10171,
316,
1731,
225,
389,
768,
2310,
6056,
23,
1651,
434,
326,
585,
225,
389,
6848,
1021,
1758,
434,
326,
3272,
6835,
225,
389,
20394,
1021,
1758,
434,
326,
25062,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
12,
3890,
1578,
389,
10171,
16,
2254,
28,
389,
2816,
2083,
16,
2254,
28,
389,
1467,
16,
1731,
1578,
389,
768,
2310,
16,
1758,
389,
6848,
16,
1758,
389,
20394,
13,
1071,
288,
203,
3639,
585,
5273,
2556,
2310,
273,
5991,
2816,
24899,
10171,
16,
389,
2816,
2083,
16,
389,
1467,
1769,
203,
3639,
3301,
273,
389,
20394,
31,
203,
3639,
6056,
23,
2816,
273,
389,
768,
2310,
31,
203,
3639,
6875,
273,
1387,
1733,
24899,
6848,
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
]
|
// File: @openzeppelin/contracts/proxy/Proxy.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback () external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive () external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/proxy/UpgradeableProxy.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*
* Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see
* {TransparentUpgradeableProxy}.
*/
contract UpgradeableProxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
Address.functionDelegateCall(_logic, _data);
}
}
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal virtual {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract");
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newImplementation)
}
}
}
// File: contracts/UpgradeableExtension.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This contract implements an upgradeable extension. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*
* Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see
* {TransparentUpgradeableProxy}.
*/
contract UpgradeableExtension is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor() public payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
}
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal virtual {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(
newImplementation == address(0x0) || Address.isContract(newImplementation),
"UpgradeableExtension: new implementation must be 0x0 or a contract"
);
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newImplementation)
}
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @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/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address62 {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address62 for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: openzeppelin-solidity/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/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 Address62 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: openzeppelin-solidity/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/math/Math.sol
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);
}
}
// File: contracts/ReentrancyGuardPausable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Reuse openzeppelin's ReentrancyGuard with Pausable feature
*/
contract ReentrancyGuardPausable {
// 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 constant _PAUSEDV1 = 4;
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 nonReentrantAndUnpaused(uint256 version) {
{
uint256 status = _status;
// On the first call to nonReentrant, _notEntered will be true
require((status & (1 << (version + 1))) == 0, "ReentrancyGuard: paused");
require((status & _ENTERED) == 0, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = status ^ _ENTERED;
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status ^= _ENTERED;
}
modifier nonReentrantAndUnpausedV1() {
{
uint256 status = _status;
// On the first call to nonReentrant, _notEntered will be true
require((status & _PAUSEDV1) == 0, "ReentrancyGuard: paused");
require((status & _ENTERED) == 0, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = status ^ _ENTERED;
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status ^= _ENTERED;
}
function _pause(uint256 flag) internal {
_status |= flag;
}
function _unpause(uint256 flag) internal {
_status &= ~flag;
}
}
// File: contracts/YERC20.sol
pragma solidity ^0.6.0;
/* TODO: Actually methods are public instead of external */
interface YERC20 is IERC20 {
function getPricePerFullShare() external view returns (uint256);
function deposit(uint256 _amount) external;
function withdraw(uint256 _shares) external;
}
// File: contracts/SmoothyV1.sol
pragma solidity ^0.6.0;
contract SmoothyV1 is ReentrancyGuardPausable, ERC20, Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 constant W_ONE = 1e18;
uint256 constant U256_1 = 1;
uint256 constant SWAP_FEE_MAX = 2e17;
uint256 constant REDEEM_FEE_MAX = 2e17;
uint256 constant ADMIN_FEE_PCT_MAX = 5e17;
/** @dev Fee collector of the contract */
address public _rewardCollector;
// Using mapping instead of array to save gas
mapping(uint256 => uint256) public _tokenInfos;
mapping(uint256 => address) public _yTokenAddresses;
// Best estimate of token balance in y pool.
// Save the gas cost of calling yToken to evaluate balanceInToken.
mapping(uint256 => uint256) public _yBalances;
/*
* _totalBalance is expected to >= sum(_getBalance()'s), where the diff is the admin fee
* collected by _collectReward().
*/
uint256 public _totalBalance;
uint256 public _swapFee = 4e14; // 1E18 means 100%
uint256 public _redeemFee = 0; // 1E18 means 100%
uint256 public _adminFeePct = 0; // % of swap/redeem fee to admin
uint256 public _adminInterestPct = 0; // % of interest to admins
uint256 public _ntokens;
uint256 constant YENABLE_OFF = 40;
uint256 constant DECM_OFF = 41;
uint256 constant TID_OFF = 46;
event Swap(
address indexed buyer,
uint256 bTokenIdIn,
uint256 bTokenIdOut,
uint256 inAmount,
uint256 outAmount
);
event SwapAll(
address indexed provider,
uint256[] amounts,
uint256 inOutFlag,
uint256 sTokenMintedOrBurned
);
event Mint(
address indexed provider,
uint256 inAmounts,
uint256 sTokenMinted
);
event Redeem(
address indexed provider,
uint256 bTokenAmount,
uint256 sTokenBurn
);
constructor (
address[] memory tokens,
address[] memory yTokens,
uint256[] memory decMultipliers,
uint256[] memory softWeights,
uint256[] memory hardWeights
)
public
ERC20("Smoothy LP Token", "syUSD")
{
require(tokens.length == yTokens.length, "tokens and ytokens must have the same length");
require(
tokens.length == decMultipliers.length,
"tokens and decMultipliers must have the same length"
);
require(
tokens.length == hardWeights.length,
"incorrect hard wt. len"
);
require(
tokens.length == softWeights.length,
"incorrect soft wt. len"
);
_rewardCollector = msg.sender;
for (uint8 i = 0; i < tokens.length; i++) {
uint256 info = uint256(tokens[i]);
require(hardWeights[i] >= softWeights[i], "hard wt. must >= soft wt.");
require(hardWeights[i] <= W_ONE, "hard wt. must <= 1e18");
info = _setHardWeight(info, hardWeights[i]);
info = _setSoftWeight(info, softWeights[i]);
info = _setDecimalMultiplier(info, decMultipliers[i]);
info = _setTID(info, i);
_yTokenAddresses[i] = yTokens[i];
// _balances[i] = 0; // no need to set
if (yTokens[i] != address(0x0)) {
info = _setYEnabled(info, true);
}
_tokenInfos[i] = info;
}
_ntokens = tokens.length;
}
/***************************************
* Methods to change a token info
***************************************/
/* return soft weight in 1e18 */
function _getSoftWeight(uint256 info) internal pure returns (uint256 w) {
return ((info >> 160) & ((U256_1 << 20) - 1)) * 1e12;
}
function _setSoftWeight(
uint256 info,
uint256 w
)
internal
pure
returns (uint256 newInfo)
{
require (w <= W_ONE, "soft weight must <= 1e18");
// Only maintain 1e6 resolution.
newInfo = info & ~(((U256_1 << 20) - 1) << 160);
newInfo = newInfo | ((w / 1e12) << 160);
}
function _getHardWeight(uint256 info) internal pure returns (uint256 w) {
return ((info >> 180) & ((U256_1 << 20) - 1)) * 1e12;
}
function _setHardWeight(
uint256 info,
uint256 w
)
internal
pure
returns (uint256 newInfo)
{
require (w <= W_ONE, "hard weight must <= 1e18");
// Only maintain 1e6 resolution.
newInfo = info & ~(((U256_1 << 20) - 1) << 180);
newInfo = newInfo | ((w / 1e12) << 180);
}
function _getDecimalMulitiplier(uint256 info) internal pure returns (uint256 dec) {
return (info >> (160 + DECM_OFF)) & ((U256_1 << 5) - 1);
}
function _setDecimalMultiplier(
uint256 info,
uint256 decm
)
internal
pure
returns (uint256 newInfo)
{
require (decm < 18, "decimal multipler is too large");
newInfo = info & ~(((U256_1 << 5) - 1) << (160 + DECM_OFF));
newInfo = newInfo | (decm << (160 + DECM_OFF));
}
function _isYEnabled(uint256 info) internal pure returns (bool) {
return (info >> (160 + YENABLE_OFF)) & 0x1 == 0x1;
}
function _setYEnabled(uint256 info, bool enabled) internal pure returns (uint256) {
if (enabled) {
return info | (U256_1 << (160 + YENABLE_OFF));
} else {
return info & ~(U256_1 << (160 + YENABLE_OFF));
}
}
function _setTID(uint256 info, uint256 tid) internal pure returns (uint256) {
require (tid < 256, "tid is too large");
require (_getTID(info) == 0, "tid cannot set again");
return info | (tid << (160 + TID_OFF));
}
function _getTID(uint256 info) internal pure returns (uint256) {
return (info >> (160 + TID_OFF)) & 0xFF;
}
/****************************************
* Owner methods
****************************************/
function pause(uint256 flag) external onlyOwner {
_pause(flag);
}
function unpause(uint256 flag) external onlyOwner {
_unpause(flag);
}
function changeRewardCollector(address newCollector) external onlyOwner {
_rewardCollector = newCollector;
}
function adjustWeights(
uint8 tid,
uint256 newSoftWeight,
uint256 newHardWeight
)
external
onlyOwner
{
require(newSoftWeight <= newHardWeight, "Soft-limit weight must <= Hard-limit weight");
require(newHardWeight <= W_ONE, "hard-limit weight must <= 1");
require(tid < _ntokens, "Backed token not exists");
_tokenInfos[tid] = _setSoftWeight(_tokenInfos[tid], newSoftWeight);
_tokenInfos[tid] = _setHardWeight(_tokenInfos[tid], newHardWeight);
}
function changeSwapFee(uint256 swapFee) external onlyOwner {
require(swapFee <= SWAP_FEE_MAX, "Swap fee must is too large");
_swapFee = swapFee;
}
function changeRedeemFee(
uint256 redeemFee
)
external
onlyOwner
{
require(redeemFee <= REDEEM_FEE_MAX, "Redeem fee is too large");
_redeemFee = redeemFee;
}
function changeAdminFeePct(uint256 pct) external onlyOwner {
require (pct <= ADMIN_FEE_PCT_MAX, "Admin fee pct is too large");
_adminFeePct = pct;
}
function changeAdminInterestPct(uint256 pct) external onlyOwner {
require (pct <= ADMIN_FEE_PCT_MAX, "Admin interest fee pct is too large");
_adminInterestPct = pct;
}
function initialize(
uint8 tid,
uint256 bTokenAmount
)
external
onlyOwner
{
require(tid < _ntokens, "Backed token not exists");
uint256 info = _tokenInfos[tid];
address addr = address(info);
IERC20(addr).safeTransferFrom(
msg.sender,
address(this),
bTokenAmount
);
_totalBalance = _totalBalance.add(bTokenAmount.mul(_normalizeBalance(info)));
_mint(msg.sender, bTokenAmount.mul(_normalizeBalance(info)));
}
function addToken(
address addr,
address yAddr,
uint256 softWeight,
uint256 hardWeight,
uint256 decMultiplier
)
external
onlyOwner
{
uint256 tid = _ntokens;
for (uint256 i = 0; i < tid; i++) {
require(address(_tokenInfos[i]) != addr, "cannot add dup token");
}
require (softWeight <= hardWeight, "soft weight must <= hard weight");
uint256 info = uint256(addr);
info = _setTID(info, tid);
info = _setYEnabled(info, yAddr != address(0x0));
info = _setSoftWeight(info, softWeight);
info = _setHardWeight(info, hardWeight);
info = _setDecimalMultiplier(info, decMultiplier);
_tokenInfos[tid] = info;
_yTokenAddresses[tid] = yAddr;
// _balances[tid] = 0; // no need to set
_ntokens = tid.add(1);
}
function setYEnabled(uint256 tid, address yAddr) external onlyOwner {
uint256 info = _tokenInfos[tid];
if (_yTokenAddresses[tid] != address(0x0)) {
// Withdraw all tokens from yToken, and clear yBalance.
uint256 pricePerShare = YERC20(_yTokenAddresses[tid]).getPricePerFullShare();
uint256 share = YERC20(_yTokenAddresses[tid]).balanceOf(address(this));
uint256 cash = _getCashBalance(info);
YERC20(_yTokenAddresses[tid]).withdraw(share);
uint256 dcash = _getCashBalance(info).sub(cash);
require(dcash >= pricePerShare.mul(share).div(W_ONE), "ytoken withdraw amount < expected");
// Update _totalBalance with interest
_updateTotalBalanceWithNewYBalance(tid, dcash);
_yBalances[tid] = 0;
}
info = _setYEnabled(info, yAddr != address(0x0));
_yTokenAddresses[tid] = yAddr;
_tokenInfos[tid] = info;
// If yAddr != 0x0, we will rebalance in next swap/mint/redeem/rebalance call.
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
* See LICENSE_LOG.md for license.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function lg2(int128 x) internal pure returns (int128) {
require (x > 0, "x must be positive");
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) {xc >>= 64; msb += 64;}
if (xc >= 0x100000000) {xc >>= 32; msb += 32;}
if (xc >= 0x10000) {xc >>= 16; msb += 16;}
if (xc >= 0x100) {xc >>= 8; msb += 8;}
if (xc >= 0x10) {xc >>= 4; msb += 4;}
if (xc >= 0x4) {xc >>= 2; msb += 2;}
if (xc >= 0x2) {msb += 1;} // No need to shift xc anymore
int256 result = (msb - 64) << 64;
uint256 ux = uint256 (x) << (127 - msb);
/* 20 iterations so that the resolution is aboout 2^-20 \approx 5e-6 */
for (int256 bit = 0x8000000000000000; bit > 0x80000000000; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256(b);
}
return int128(result);
}
function _safeToInt128(uint256 x) internal pure returns (int128 y) {
y = int128(x);
require(x == uint256(y), "Conversion to int128 failed");
return y;
}
/**
* @dev Return the approx logarithm of a value with log(x) where x <= 1.1.
* All values are in integers with (1e18 == 1.0).
*
* Requirements:
*
* - input value x must be greater than 1e18
*/
function _logApprox(uint256 x) internal pure returns (uint256 y) {
uint256 one = W_ONE;
require(x >= one, "logApprox: x must >= 1");
uint256 z = x - one;
uint256 zz = z.mul(z).div(one);
uint256 zzz = zz.mul(z).div(one);
uint256 zzzz = zzz.mul(z).div(one);
uint256 zzzzz = zzzz.mul(z).div(one);
return z.sub(zz.div(2)).add(zzz.div(3)).sub(zzzz.div(4)).add(zzzzz.div(5));
}
/**
* @dev Return the logarithm of a value.
* All values are in integers with (1e18 == 1.0).
*
* Requirements:
*
* - input value x must be greater than 1e18
*/
function _log(uint256 x) internal pure returns (uint256 y) {
require(x >= W_ONE, "log(x): x must be greater than 1");
require(x < (W_ONE << 63), "log(x): x is too large");
if (x <= W_ONE.add(W_ONE.div(10))) {
return _logApprox(x);
}
/* Convert to 64.64 float point */
int128 xx = _safeToInt128((x << 64) / W_ONE);
int128 yy = lg2(xx);
/* log(2) * 1e18 \approx 693147180559945344 */
y = (uint256(yy) * 693147180559945344) >> 64;
return y;
}
/**
* Return weights and cached balances of all tokens
* Note that the cached balance does not include the accrued interest since last rebalance.
*/
function _getBalancesAndWeights()
internal
view
returns (uint256[] memory balances, uint256[] memory softWeights, uint256[] memory hardWeights, uint256 totalBalance)
{
uint256 ntokens = _ntokens;
balances = new uint256[](ntokens);
softWeights = new uint256[](ntokens);
hardWeights = new uint256[](ntokens);
totalBalance = 0;
for (uint8 i = 0; i < ntokens; i++) {
uint256 info = _tokenInfos[i];
balances[i] = _getCashBalance(info);
if (_isYEnabled(info)) {
balances[i] = balances[i].add(_yBalances[i]);
}
totalBalance = totalBalance.add(balances[i]);
softWeights[i] = _getSoftWeight(info);
hardWeights[i] = _getHardWeight(info);
}
}
function _getBalancesAndInfos()
internal
view
returns (uint256[] memory balances, uint256[] memory infos, uint256 totalBalance)
{
uint256 ntokens = _ntokens;
balances = new uint256[](ntokens);
infos = new uint256[](ntokens);
totalBalance = 0;
for (uint8 i = 0; i < ntokens; i++) {
infos[i] = _tokenInfos[i];
balances[i] = _getCashBalance(infos[i]);
if (_isYEnabled(infos[i])) {
balances[i] = balances[i].add(_yBalances[i]);
}
totalBalance = totalBalance.add(balances[i]);
}
}
function _getBalance(uint256 info) internal view returns (uint256 balance) {
balance = _getCashBalance(info);
if (_isYEnabled(info)) {
balance = balance.add(_yBalances[_getTID(info)]);
}
}
function getBalance(uint256 tid) public view returns (uint256) {
return _getBalance(_tokenInfos[tid]);
}
function _normalizeBalance(uint256 info) internal pure returns (uint256) {
uint256 decm = _getDecimalMulitiplier(info);
return 10 ** decm;
}
/* @dev Return normalized cash balance of a token */
function _getCashBalance(uint256 info) internal view returns (uint256) {
return IERC20(address(info)).balanceOf(address(this))
.mul(_normalizeBalance(info));
}
function _getBalanceDetail(
uint256 info
)
internal
view
returns (uint256 pricePerShare, uint256 cashUnnormalized, uint256 yBalanceUnnormalized)
{
address yAddr = _yTokenAddresses[_getTID(info)];
pricePerShare = YERC20(yAddr).getPricePerFullShare();
cashUnnormalized = IERC20(address(info)).balanceOf(address(this));
uint256 share = YERC20(yAddr).balanceOf(address(this));
yBalanceUnnormalized = share.mul(pricePerShare).div(W_ONE);
}
/**************************************************************************************
* Methods for rebalance cash reserve
* After rebalancing, we will have cash reserve equaling to 10% of total balance
* There are two conditions to trigger a rebalancing
* - if there is insufficient cash for withdraw; or
* - if the cash reserve is greater than 20% of total balance.
* Note that we use a cached version of total balance to avoid high gas cost on calling
* getPricePerFullShare().
*************************************************************************************/
function _updateTotalBalanceWithNewYBalance(
uint256 tid,
uint256 yBalanceNormalizedNew
)
internal
{
uint256 adminFee = 0;
uint256 yBalanceNormalizedOld = _yBalances[tid];
// They yBalance should not be decreasing, but just in case,
if (yBalanceNormalizedNew >= yBalanceNormalizedOld) {
adminFee = (yBalanceNormalizedNew - yBalanceNormalizedOld).mul(_adminInterestPct).div(W_ONE);
}
_totalBalance = _totalBalance
.sub(yBalanceNormalizedOld)
.add(yBalanceNormalizedNew)
.sub(adminFee);
}
function _rebalanceReserve(
uint256 info
)
internal
{
require(_isYEnabled(info), "yToken must be enabled for rebalancing");
uint256 pricePerShare;
uint256 cashUnnormalized;
uint256 yBalanceUnnormalized;
(pricePerShare, cashUnnormalized, yBalanceUnnormalized) = _getBalanceDetail(info);
uint256 tid = _getTID(info);
// Update _totalBalance with interest
_updateTotalBalanceWithNewYBalance(tid, yBalanceUnnormalized.mul(_normalizeBalance(info)));
uint256 targetCash = yBalanceUnnormalized.add(cashUnnormalized).div(10);
if (cashUnnormalized > targetCash) {
uint256 depositAmount = cashUnnormalized.sub(targetCash);
// Reset allowance to bypass possible allowance check (e.g., USDT)
IERC20(address(info)).safeApprove(_yTokenAddresses[tid], 0);
IERC20(address(info)).safeApprove(_yTokenAddresses[tid], depositAmount);
// Calculate acutal deposit in the case that some yTokens may return partial deposit.
uint256 balanceBefore = IERC20(address(info)).balanceOf(address(this));
YERC20(_yTokenAddresses[tid]).deposit(depositAmount);
uint256 actualDeposit = balanceBefore.sub(IERC20(address(info)).balanceOf(address(this)));
_yBalances[tid] = yBalanceUnnormalized.add(actualDeposit).mul(_normalizeBalance(info));
} else {
uint256 expectedWithdraw = targetCash.sub(cashUnnormalized);
if (expectedWithdraw == 0) {
return;
}
uint256 balanceBefore = IERC20(address(info)).balanceOf(address(this));
// Withdraw +1 wei share to make sure actual withdraw >= expected.
YERC20(_yTokenAddresses[tid]).withdraw(expectedWithdraw.mul(W_ONE).div(pricePerShare).add(1));
uint256 actualWithdraw = IERC20(address(info)).balanceOf(address(this)).sub(balanceBefore);
require(actualWithdraw >= expectedWithdraw, "insufficient cash withdrawn from yToken");
_yBalances[tid] = yBalanceUnnormalized.sub(actualWithdraw).mul(_normalizeBalance(info));
}
}
/* @dev Forcibly rebalance so that cash reserve is about 10% of total. */
function rebalanceReserve(
uint256 tid
)
external
nonReentrantAndUnpausedV1
{
_rebalanceReserve(_tokenInfos[tid]);
}
/*
* @dev Rebalance the cash reserve so that
* cash reserve consists of 10% of total balance after substracting amountUnnormalized.
*
* Assume that current cash reserve < amountUnnormalized.
*/
function _rebalanceReserveSubstract(
uint256 info,
uint256 amountUnnormalized
)
internal
{
require(_isYEnabled(info), "yToken must be enabled for rebalancing");
uint256 pricePerShare;
uint256 cashUnnormalized;
uint256 yBalanceUnnormalized;
(pricePerShare, cashUnnormalized, yBalanceUnnormalized) = _getBalanceDetail(info);
// Update _totalBalance with interest
_updateTotalBalanceWithNewYBalance(
_getTID(info),
yBalanceUnnormalized.mul(_normalizeBalance(info))
);
// Evaluate the shares to withdraw so that cash = 10% of total
uint256 expectedWithdraw = cashUnnormalized.add(yBalanceUnnormalized).sub(
amountUnnormalized).div(10).add(amountUnnormalized).sub(cashUnnormalized);
if (expectedWithdraw == 0) {
return;
}
// Withdraw +1 wei share to make sure actual withdraw >= expected.
uint256 withdrawShares = expectedWithdraw.mul(W_ONE).div(pricePerShare).add(1);
uint256 balanceBefore = IERC20(address(info)).balanceOf(address(this));
YERC20(_yTokenAddresses[_getTID(info)]).withdraw(withdrawShares);
uint256 actualWithdraw = IERC20(address(info)).balanceOf(address(this)).sub(balanceBefore);
require(actualWithdraw >= expectedWithdraw, "insufficient cash withdrawn from yToken");
_yBalances[_getTID(info)] = yBalanceUnnormalized.sub(actualWithdraw)
.mul(_normalizeBalance(info));
}
/* @dev Transfer the amount of token out. Rebalance the cash reserve if needed */
function _transferOut(
uint256 info,
uint256 amountUnnormalized,
uint256 adminFee
)
internal
{
uint256 amountNormalized = amountUnnormalized.mul(_normalizeBalance(info));
if (_isYEnabled(info)) {
if (IERC20(address(info)).balanceOf(address(this)) < amountUnnormalized) {
_rebalanceReserveSubstract(info, amountUnnormalized);
}
}
IERC20(address(info)).safeTransfer(
msg.sender,
amountUnnormalized
);
_totalBalance = _totalBalance
.sub(amountNormalized)
.sub(adminFee.mul(_normalizeBalance(info)));
}
/* @dev Transfer the amount of token in. Rebalance the cash reserve if needed */
function _transferIn(
uint256 info,
uint256 amountUnnormalized
)
internal
{
uint256 amountNormalized = amountUnnormalized.mul(_normalizeBalance(info));
IERC20(address(info)).safeTransferFrom(
msg.sender,
address(this),
amountUnnormalized
);
_totalBalance = _totalBalance.add(amountNormalized);
// If there is saving ytoken, save the balance in _balance.
if (_isYEnabled(info)) {
uint256 tid = _getTID(info);
/* Check rebalance if needed */
uint256 cash = _getCashBalance(info);
if (cash > cash.add(_yBalances[tid]).mul(2).div(10)) {
_rebalanceReserve(info);
}
}
}
/**************************************************************************************
* Methods for minting LP tokens
*************************************************************************************/
/*
* @dev Return the amount of sUSD should be minted after depositing bTokenAmount into the pool
* @param bTokenAmountNormalized - normalized amount of token to be deposited
* @param oldBalance - normalized amount of all tokens before the deposit
* @param oldTokenBlance - normalized amount of the balance of the token to be deposited in the pool
* @param softWeight - percentage that will incur penalty if the resulting token percentage is greater
* @param hardWeight - maximum percentage of the token
*/
function _getMintAmount(
uint256 bTokenAmountNormalized,
uint256 oldBalance,
uint256 oldTokenBalance,
uint256 softWeight,
uint256 hardWeight
)
internal
pure
returns (uint256 s)
{
/* Evaluate new percentage */
uint256 newBalance = oldBalance.add(bTokenAmountNormalized);
uint256 newTokenBalance = oldTokenBalance.add(bTokenAmountNormalized);
/* If new percentage <= soft weight, no penalty */
if (newTokenBalance.mul(W_ONE) <= softWeight.mul(newBalance)) {
return bTokenAmountNormalized;
}
require (
newTokenBalance.mul(W_ONE) <= hardWeight.mul(newBalance),
"mint: new percentage exceeds hard weight"
);
s = 0;
/* if new percentage <= soft weight, get the beginning of integral with penalty. */
if (oldTokenBalance.mul(W_ONE) <= softWeight.mul(oldBalance)) {
s = oldBalance.mul(softWeight).sub(oldTokenBalance.mul(W_ONE)).div(W_ONE.sub(softWeight));
}
// bx + (tx - bx) * (w - 1) / (w - v) + (S - x) * ln((S + tx) / (S + bx)) / (w - v)
uint256 t;
{ // avoid stack too deep error
uint256 ldelta = _log(newBalance.mul(W_ONE).div(oldBalance.add(s)));
t = oldBalance.sub(oldTokenBalance).mul(ldelta);
}
t = t.sub(bTokenAmountNormalized.sub(s).mul(W_ONE.sub(hardWeight)));
t = t.div(hardWeight.sub(softWeight));
s = s.add(t);
require(s <= bTokenAmountNormalized, "penalty should be positive");
}
/*
* @dev Given the token id and the amount to be deposited, return the amount of lp token
*/
function getMintAmount(
uint256 bTokenIdx,
uint256 bTokenAmount
)
public
view
returns (uint256 lpTokenAmount)
{
require(bTokenAmount > 0, "Amount must be greater than 0");
uint256 info = _tokenInfos[bTokenIdx];
require(info != 0, "Backed token is not found!");
// Obtain normalized balances
uint256 bTokenAmountNormalized = bTokenAmount.mul(_normalizeBalance(info));
// Gas saving: Use cached totalBalance with accrued interest since last rebalance.
uint256 totalBalance = _totalBalance;
uint256 sTokenAmount = _getMintAmount(
bTokenAmountNormalized,
totalBalance,
_getBalance(info),
_getSoftWeight(info),
_getHardWeight(info)
);
return sTokenAmount.mul(totalSupply()).div(totalBalance);
}
/*
* @dev Given the token id and the amount to be deposited, mint lp token
*/
function mint(
uint256 bTokenIdx,
uint256 bTokenAmount,
uint256 lpTokenMintedMin
)
external
nonReentrantAndUnpausedV1
{
uint256 lpTokenAmount = getMintAmount(bTokenIdx, bTokenAmount);
require(
lpTokenAmount >= lpTokenMintedMin,
"lpToken minted should >= minimum lpToken asked"
);
_transferIn(_tokenInfos[bTokenIdx], bTokenAmount);
_mint(msg.sender, lpTokenAmount);
emit Mint(msg.sender, bTokenAmount, lpTokenAmount);
}
/**************************************************************************************
* Methods for redeeming LP tokens
*************************************************************************************/
/*
* @dev Return number of sUSD that is needed to redeem corresponding amount of token for another
* token
* Withdrawing a token will result in increased percentage of other tokens, where
* the function is used to calculate the penalty incured by the increase of one token.
* @param totalBalance - normalized amount of the sum of all tokens
* @param tokenBlance - normalized amount of the balance of a non-withdrawn token
* @param redeemAount - normalized amount of the token to be withdrawn
* @param softWeight - percentage that will incur penalty if the resulting token percentage is greater
* @param hardWeight - maximum percentage of the token
*/
function _redeemPenaltyFor(
uint256 totalBalance,
uint256 tokenBalance,
uint256 redeemAmount,
uint256 softWeight,
uint256 hardWeight
)
internal
pure
returns (uint256)
{
uint256 newTotalBalance = totalBalance.sub(redeemAmount);
/* Soft weight is satisfied. No penalty is incurred */
if (tokenBalance.mul(W_ONE) <= newTotalBalance.mul(softWeight)) {
return 0;
}
require (
tokenBalance.mul(W_ONE) <= newTotalBalance.mul(hardWeight),
"redeem: hard-limit weight is broken"
);
uint256 bx = 0;
// Evaluate the beginning of the integral for broken soft weight
if (tokenBalance.mul(W_ONE) < totalBalance.mul(softWeight)) {
bx = totalBalance.sub(tokenBalance.mul(W_ONE).div(softWeight));
}
// x * (w - v) / w / w * ln(1 + (tx - bx) * w / (w * (S - tx) - x)) - (tx - bx) * v / w
uint256 tdelta = tokenBalance.mul(
_log(W_ONE.add(redeemAmount.sub(bx).mul(hardWeight).div(hardWeight.mul(newTotalBalance).div(W_ONE).sub(tokenBalance)))));
uint256 s1 = tdelta.mul(hardWeight.sub(softWeight))
.div(hardWeight).div(hardWeight);
uint256 s2 = redeemAmount.sub(bx).mul(softWeight).div(hardWeight);
return s1.sub(s2);
}
/*
* @dev Return number of sUSD that is needed to redeem corresponding amount of token
* Withdrawing a token will result in increased percentage of other tokens, where
* the function is used to calculate the penalty incured by the increase.
* @param bTokenIdx - token id to be withdrawn
* @param totalBalance - normalized amount of the sum of all tokens
* @param balances - normalized amount of the balance of each token
* @param softWeights - percentage that will incur penalty if the resulting token percentage is greater
* @param hardWeights - maximum percentage of the token
* @param redeemAount - normalized amount of the token to be withdrawn
*/
function _redeemPenaltyForAll(
uint256 bTokenIdx,
uint256 totalBalance,
uint256[] memory balances,
uint256[] memory softWeights,
uint256[] memory hardWeights,
uint256 redeemAmount
)
internal
pure
returns (uint256)
{
uint256 s = 0;
for (uint256 k = 0; k < balances.length; k++) {
if (k == bTokenIdx) {
continue;
}
s = s.add(
_redeemPenaltyFor(totalBalance, balances[k], redeemAmount, softWeights[k], hardWeights[k]));
}
return s;
}
/*
* @dev Calculate the derivative of the penalty function.
* Same parameters as _redeemPenaltyFor.
*/
function _redeemPenaltyDerivativeForOne(
uint256 totalBalance,
uint256 tokenBalance,
uint256 redeemAmount,
uint256 softWeight,
uint256 hardWeight
)
internal
pure
returns (uint256)
{
uint256 dfx = W_ONE;
uint256 newTotalBalance = totalBalance.sub(redeemAmount);
/* Soft weight is satisfied. No penalty is incurred */
if (tokenBalance.mul(W_ONE) <= newTotalBalance.mul(softWeight)) {
return dfx;
}
// dx = dx + x * (w - v) / (w * (S - tx) - x) / w - v / w
return dfx.add(tokenBalance.mul(hardWeight.sub(softWeight))
.div(hardWeight.mul(newTotalBalance).div(W_ONE).sub(tokenBalance)))
.sub(softWeight.mul(W_ONE).div(hardWeight));
}
/*
* @dev Calculate the derivative of the penalty function.
* Same parameters as _redeemPenaltyForAll.
*/
function _redeemPenaltyDerivativeForAll(
uint256 bTokenIdx,
uint256 totalBalance,
uint256[] memory balances,
uint256[] memory softWeights,
uint256[] memory hardWeights,
uint256 redeemAmount
)
internal
pure
returns (uint256)
{
uint256 dfx = W_ONE;
uint256 newTotalBalance = totalBalance.sub(redeemAmount);
for (uint256 k = 0; k < balances.length; k++) {
if (k == bTokenIdx) {
continue;
}
/* Soft weight is satisfied. No penalty is incurred */
uint256 softWeight = softWeights[k];
uint256 balance = balances[k];
if (balance.mul(W_ONE) <= newTotalBalance.mul(softWeight)) {
continue;
}
// dx = dx + x * (w - v) / (w * (S - tx) - x) / w - v / w
uint256 hardWeight = hardWeights[k];
dfx = dfx.add(balance.mul(hardWeight.sub(softWeight))
.div(hardWeight.mul(newTotalBalance).div(W_ONE).sub(balance)))
.sub(softWeight.mul(W_ONE).div(hardWeight));
}
return dfx;
}
/*
* @dev Given the amount of sUSD to be redeemed, find the max token can be withdrawn
* This function is for swap only.
* @param tidOutBalance - the balance of the token to be withdrawn
* @param totalBalance - total balance of all tokens
* @param tidInBalance - the balance of the token to be deposited
* @param sTokenAmount - the amount of sUSD to be redeemed
* @param softWeight/hardWeight - normalized weights for the token to be withdrawn.
*/
function _redeemFindOne(
uint256 tidOutBalance,
uint256 totalBalance,
uint256 tidInBalance,
uint256 sTokenAmount,
uint256 softWeight,
uint256 hardWeight
)
internal
pure
returns (uint256)
{
uint256 redeemAmountNormalized = Math.min(
sTokenAmount,
tidOutBalance.mul(999).div(1000)
);
for (uint256 i = 0; i < 256; i++) {
uint256 sNeeded = redeemAmountNormalized.add(
_redeemPenaltyFor(
totalBalance,
tidInBalance,
redeemAmountNormalized,
softWeight,
hardWeight
));
uint256 fx = 0;
if (sNeeded > sTokenAmount) {
fx = sNeeded - sTokenAmount;
} else {
fx = sTokenAmount - sNeeded;
}
// penalty < 1e-5 of out amount
if (fx < redeemAmountNormalized / 100000) {
require(redeemAmountNormalized <= sTokenAmount, "Redeem error: out amount > lp amount");
require(redeemAmountNormalized <= tidOutBalance, "Redeem error: insufficient balance");
return redeemAmountNormalized;
}
uint256 dfx = _redeemPenaltyDerivativeForOne(
totalBalance,
tidInBalance,
redeemAmountNormalized,
softWeight,
hardWeight
);
if (sNeeded > sTokenAmount) {
redeemAmountNormalized = redeemAmountNormalized.sub(fx.mul(W_ONE).div(dfx));
} else {
redeemAmountNormalized = redeemAmountNormalized.add(fx.mul(W_ONE).div(dfx));
}
}
require (false, "cannot find proper resolution of fx");
}
/*
* @dev Given the amount of sUSD token to be redeemed, find the max token can be withdrawn
* @param bTokenIdx - the id of the token to be withdrawn
* @param sTokenAmount - the amount of sUSD token to be redeemed
* @param totalBalance - total balance of all tokens
* @param balances/softWeight/hardWeight - normalized balances/weights of all tokens
*/
function _redeemFind(
uint256 bTokenIdx,
uint256 sTokenAmount,
uint256 totalBalance,
uint256[] memory balances,
uint256[] memory softWeights,
uint256[] memory hardWeights
)
internal
pure
returns (uint256)
{
uint256 bTokenAmountNormalized = Math.min(
sTokenAmount,
balances[bTokenIdx].mul(999).div(1000)
);
for (uint256 i = 0; i < 256; i++) {
uint256 sNeeded = bTokenAmountNormalized.add(
_redeemPenaltyForAll(
bTokenIdx,
totalBalance,
balances,
softWeights,
hardWeights,
bTokenAmountNormalized
));
uint256 fx = 0;
if (sNeeded > sTokenAmount) {
fx = sNeeded - sTokenAmount;
} else {
fx = sTokenAmount - sNeeded;
}
// penalty < 1e-5 of out amount
if (fx < bTokenAmountNormalized / 100000) {
require(bTokenAmountNormalized <= sTokenAmount, "Redeem error: out amount > lp amount");
require(bTokenAmountNormalized <= balances[bTokenIdx], "Redeem error: insufficient balance");
return bTokenAmountNormalized;
}
uint256 dfx = _redeemPenaltyDerivativeForAll(
bTokenIdx,
totalBalance,
balances,
softWeights,
hardWeights,
bTokenAmountNormalized
);
if (sNeeded > sTokenAmount) {
bTokenAmountNormalized = bTokenAmountNormalized.sub(fx.mul(W_ONE).div(dfx));
} else {
bTokenAmountNormalized = bTokenAmountNormalized.add(fx.mul(W_ONE).div(dfx));
}
}
require (false, "cannot find proper resolution of fx");
}
/*
* @dev Given token id and LP token amount, return the max amount of token can be withdrawn
* @param tid - the id of the token to be withdrawn
* @param lpTokenAmount - the amount of LP token
*/
function _getRedeemByLpTokenAmount(
uint256 tid,
uint256 lpTokenAmount
)
internal
view
returns (uint256 bTokenAmount, uint256 totalBalance, uint256 adminFee)
{
require(lpTokenAmount > 0, "Amount must be greater than 0");
uint256 info = _tokenInfos[tid];
require(info != 0, "Backed token is not found!");
// Obtain normalized balances.
// Gas saving: Use cached balances/totalBalance without accrued interest since last rebalance.
uint256[] memory balances;
uint256[] memory softWeights;
uint256[] memory hardWeights;
(balances, softWeights, hardWeights, totalBalance) = _getBalancesAndWeights();
bTokenAmount = _redeemFind(
tid,
lpTokenAmount.mul(totalBalance).div(totalSupply()),
totalBalance,
balances,
softWeights,
hardWeights
).div(_normalizeBalance(info));
uint256 fee = bTokenAmount.mul(_redeemFee).div(W_ONE);
adminFee = fee.mul(_adminFeePct).div(W_ONE);
bTokenAmount = bTokenAmount.sub(fee);
}
function getRedeemByLpTokenAmount(
uint256 tid,
uint256 lpTokenAmount
)
public
view
returns (uint256 bTokenAmount)
{
(bTokenAmount,,) = _getRedeemByLpTokenAmount(tid, lpTokenAmount);
}
function redeemByLpToken(
uint256 bTokenIdx,
uint256 lpTokenAmount,
uint256 bTokenMin
)
external
nonReentrantAndUnpausedV1
{
(uint256 bTokenAmount, uint256 totalBalance, uint256 adminFee) = _getRedeemByLpTokenAmount(
bTokenIdx,
lpTokenAmount
);
require(bTokenAmount >= bTokenMin, "bToken returned < min bToken asked");
// Make sure _totalBalance == sum(balances)
_collectReward(totalBalance);
_burn(msg.sender, lpTokenAmount);
_transferOut(_tokenInfos[bTokenIdx], bTokenAmount, adminFee);
emit Redeem(msg.sender, bTokenAmount, lpTokenAmount);
}
/* @dev Redeem a specific token from the pool.
* Fee will be incured. Will incur penalty if the pool is unbalanced.
*/
function redeem(
uint256 bTokenIdx,
uint256 bTokenAmount,
uint256 lpTokenBurnedMax
)
external
nonReentrantAndUnpausedV1
{
require(bTokenAmount > 0, "Amount must be greater than 0");
uint256 info = _tokenInfos[bTokenIdx];
require (info != 0, "Backed token is not found!");
// Obtain normalized balances.
// Gas saving: Use cached balances/totalBalance without accrued interest since last rebalance.
(
uint256[] memory balances,
uint256[] memory softWeights,
uint256[] memory hardWeights,
uint256 totalBalance
) = _getBalancesAndWeights();
uint256 bTokenAmountNormalized = bTokenAmount.mul(_normalizeBalance(info));
require(balances[bTokenIdx] >= bTokenAmountNormalized, "Insufficient token to redeem");
_collectReward(totalBalance);
uint256 lpAmount = bTokenAmountNormalized.add(
_redeemPenaltyForAll(
bTokenIdx,
totalBalance,
balances,
softWeights,
hardWeights,
bTokenAmountNormalized
)).mul(totalSupply()).div(totalBalance);
require(lpAmount <= lpTokenBurnedMax, "burned token should <= maximum lpToken offered");
_burn(msg.sender, lpAmount);
/* Transfer out the token after deducting the fee. Rebalance cash reserve if needed */
uint256 fee = bTokenAmount.mul(_redeemFee).div(W_ONE);
_transferOut(
_tokenInfos[bTokenIdx],
bTokenAmount.sub(fee),
fee.mul(_adminFeePct).div(W_ONE)
);
emit Redeem(msg.sender, bTokenAmount, lpAmount);
}
/**************************************************************************************
* Methods for swapping tokens
*************************************************************************************/
/*
* @dev Return the maximum amount of token can be withdrawn after depositing another token.
* @param bTokenIdIn - the id of the token to be deposited
* @param bTokenIdOut - the id of the token to be withdrawn
* @param bTokenInAmount - the amount (unnormalized) of the token to be deposited
*/
function getSwapAmount(
uint256 bTokenIdxIn,
uint256 bTokenIdxOut,
uint256 bTokenInAmount
)
external
view
returns (uint256 bTokenOutAmount)
{
uint256 infoIn = _tokenInfos[bTokenIdxIn];
uint256 infoOut = _tokenInfos[bTokenIdxOut];
(bTokenOutAmount,) = _getSwapAmount(infoIn, infoOut, bTokenInAmount);
}
function _getSwapAmount(
uint256 infoIn,
uint256 infoOut,
uint256 bTokenInAmount
)
internal
view
returns (uint256 bTokenOutAmount, uint256 adminFee)
{
require(bTokenInAmount > 0, "Amount must be greater than 0");
require(infoIn != 0, "Backed token is not found!");
require(infoOut != 0, "Backed token is not found!");
require (infoIn != infoOut, "Tokens for swap must be different!");
// Gas saving: Use cached totalBalance without accrued interest since last rebalance.
// Here we assume that the interest earned from the underlying platform is too small to
// impact the result significantly.
uint256 totalBalance = _totalBalance;
uint256 tidInBalance = _getBalance(infoIn);
uint256 sMinted = 0;
uint256 softWeight = _getSoftWeight(infoIn);
uint256 hardWeight = _getHardWeight(infoIn);
{ // avoid stack too deep error
uint256 bTokenInAmountNormalized = bTokenInAmount.mul(_normalizeBalance(infoIn));
sMinted = _getMintAmount(
bTokenInAmountNormalized,
totalBalance,
tidInBalance,
softWeight,
hardWeight
);
totalBalance = totalBalance.add(bTokenInAmountNormalized);
tidInBalance = tidInBalance.add(bTokenInAmountNormalized);
}
uint256 tidOutBalance = _getBalance(infoOut);
// Find the bTokenOutAmount, only account for penalty from bTokenIdxIn
// because other tokens should not have penalty since
// bTokenOutAmount <= sMinted <= bTokenInAmount (normalized), and thus
// for other tokens, the percentage decreased by bTokenInAmount will be
// >= the percetnage increased by bTokenOutAmount.
bTokenOutAmount = _redeemFindOne(
tidOutBalance,
totalBalance,
tidInBalance,
sMinted,
softWeight,
hardWeight
).div(_normalizeBalance(infoOut));
uint256 fee = bTokenOutAmount.mul(_swapFee).div(W_ONE);
adminFee = fee.mul(_adminFeePct).div(W_ONE);
bTokenOutAmount = bTokenOutAmount.sub(fee);
}
/*
* @dev Swap a token to another.
* @param bTokenIdIn - the id of the token to be deposited
* @param bTokenIdOut - the id of the token to be withdrawn
* @param bTokenInAmount - the amount (unnormalized) of the token to be deposited
* @param bTokenOutMin - the mininum amount (unnormalized) token that is expected to be withdrawn
*/
function swap(
uint256 bTokenIdxIn,
uint256 bTokenIdxOut,
uint256 bTokenInAmount,
uint256 bTokenOutMin
)
external
nonReentrantAndUnpausedV1
{
uint256 infoIn = _tokenInfos[bTokenIdxIn];
uint256 infoOut = _tokenInfos[bTokenIdxOut];
(
uint256 bTokenOutAmount,
uint256 adminFee
) = _getSwapAmount(infoIn, infoOut, bTokenInAmount);
require(bTokenOutAmount >= bTokenOutMin, "Returned bTokenAmount < asked");
_transferIn(infoIn, bTokenInAmount);
_transferOut(infoOut, bTokenOutAmount, adminFee);
emit Swap(
msg.sender,
bTokenIdxIn,
bTokenIdxOut,
bTokenInAmount,
bTokenOutAmount
);
}
/*
* @dev Swap tokens given all token amounts
* The amounts are pre-fee amounts, and the user will provide max fee expected.
* Currently, do not support penalty.
* @param inOutFlag - 0 means deposit, and 1 means withdraw with highest bit indicating mint/burn lp token
* @param lpTokenMintedMinOrBurnedMax - amount of lp token to be minted/burnt
* @param maxFee - maximum percentage of fee will be collected for withdrawal
* @param amounts - list of unnormalized amounts of each token
*/
function swapAll(
uint256 inOutFlag,
uint256 lpTokenMintedMinOrBurnedMax,
uint256 maxFee,
uint256[] calldata amounts
)
external
nonReentrantAndUnpausedV1
{
// Gas saving: Use cached balances/totalBalance without accrued interest since last rebalance.
(
uint256[] memory balances,
uint256[] memory infos,
uint256 oldTotalBalance
) = _getBalancesAndInfos();
// Make sure _totalBalance = oldTotalBalance = sum(_getBalance()'s)
_collectReward(oldTotalBalance);
require (amounts.length == balances.length, "swapAll amounts length != ntokens");
uint256 newTotalBalance = 0;
uint256 depositAmount = 0;
{ // avoid stack too deep error
uint256[] memory newBalances = new uint256[](balances.length);
for (uint256 i = 0; i < balances.length; i++) {
uint256 normalizedAmount = _normalizeBalance(infos[i]).mul(amounts[i]);
if (((inOutFlag >> i) & 1) == 0) {
// In
depositAmount = depositAmount.add(normalizedAmount);
newBalances[i] = balances[i].add(normalizedAmount);
} else {
// Out
newBalances[i] = balances[i].sub(normalizedAmount);
}
newTotalBalance = newTotalBalance.add(newBalances[i]);
}
for (uint256 i = 0; i < balances.length; i++) {
// If there is no mint/redeem, and the new total balance >= old one,
// then the weight must be non-increasing and thus there is no penalty.
if (amounts[i] == 0 && newTotalBalance >= oldTotalBalance) {
continue;
}
/*
* Accept the new amount if the following is satisfied
* np_i <= max(p_i, w_i)
*/
if (newBalances[i].mul(W_ONE) <= newTotalBalance.mul(_getSoftWeight(infos[i]))) {
continue;
}
// If no tokens in the pool, only weight contraints will be applied.
require(
oldTotalBalance != 0 &&
newBalances[i].mul(oldTotalBalance) <= newTotalBalance.mul(balances[i]),
"penalty is not supported in swapAll now"
);
}
}
// Calculate fee rate and mint/burn LP tokens
uint256 feeRate = 0;
uint256 lpMintedOrBurned = 0;
if (newTotalBalance == oldTotalBalance) {
// Swap only. No need to burn or mint.
lpMintedOrBurned = 0;
feeRate = _swapFee;
} else if (((inOutFlag >> 255) & 1) == 0) {
require (newTotalBalance >= oldTotalBalance, "swapAll mint: new total balance must >= old total balance");
lpMintedOrBurned = newTotalBalance.sub(oldTotalBalance).mul(totalSupply()).div(oldTotalBalance);
require(lpMintedOrBurned >= lpTokenMintedMinOrBurnedMax, "LP tokend minted < asked");
feeRate = _swapFee;
_mint(msg.sender, lpMintedOrBurned);
} else {
require (newTotalBalance <= oldTotalBalance, "swapAll redeem: new total balance must <= old total balance");
lpMintedOrBurned = oldTotalBalance.sub(newTotalBalance).mul(totalSupply()).div(oldTotalBalance);
require(lpMintedOrBurned <= lpTokenMintedMinOrBurnedMax, "LP tokend burned > offered");
uint256 withdrawAmount = oldTotalBalance - newTotalBalance;
/*
* The fee is determined by swapAmount * swap_fee + withdrawAmount * withdraw_fee,
* where swapAmount = depositAmount if withdrawAmount >= 0.
*/
feeRate = _swapFee.mul(depositAmount).add(_redeemFee.mul(withdrawAmount)).div(depositAmount + withdrawAmount);
_burn(msg.sender, lpMintedOrBurned);
}
emit SwapAll(msg.sender, amounts, inOutFlag, lpMintedOrBurned);
require (feeRate <= maxFee, "swapAll fee is greater than max fee user offered");
for (uint256 i = 0; i < balances.length; i++) {
if (amounts[i] == 0) {
continue;
}
if (((inOutFlag >> i) & 1) == 0) {
// In
_transferIn(infos[i], amounts[i]);
} else {
// Out (with fee)
uint256 fee = amounts[i].mul(feeRate).div(W_ONE);
uint256 adminFee = fee.mul(_adminFeePct).div(W_ONE);
_transferOut(infos[i], amounts[i].sub(fee), adminFee);
}
}
}
/**************************************************************************************
* Methods for others
*************************************************************************************/
/* @dev Collect admin fee so that _totalBalance == sum(_getBalances()'s) */
function _collectReward(uint256 totalBalance) internal {
uint256 oldTotalBalance = _totalBalance;
if (totalBalance != oldTotalBalance) {
if (totalBalance > oldTotalBalance) {
_mint(_rewardCollector, totalSupply().mul(totalBalance - oldTotalBalance).div(oldTotalBalance));
}
_totalBalance = totalBalance;
}
}
/* @dev Collect admin fee. Can be called by anyone */
function collectReward()
external
nonReentrantAndUnpausedV1
{
(,,,uint256 totalBalance) = _getBalancesAndWeights();
_collectReward(totalBalance);
}
function getTokenStats(uint256 bTokenIdx)
public
view
returns (uint256 softWeight, uint256 hardWeight, uint256 balance, uint256 decimals)
{
require(bTokenIdx < _ntokens, "Backed token is not found!");
uint256 info = _tokenInfos[bTokenIdx];
balance = _getBalance(info).div(_normalizeBalance(info));
softWeight = _getSoftWeight(info);
hardWeight = _getHardWeight(info);
decimals = ERC20(address(info)).decimals();
}
}
// File: contracts/Root.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract Root is UpgradeableExtension, SmoothyV1 {
constructor(
address[] memory tokens,
address[] memory yTokens,
uint256[] memory decMultipliers,
uint256[] memory softWeights,
uint256[] memory hardWeights
)
public
UpgradeableExtension()
SmoothyV1(tokens, yTokens, decMultipliers, softWeights, hardWeights)
{ }
function upgradeTo(address newImplementation) external onlyOwner {
_upgradeTo(newImplementation);
}
} | @dev Given the token id and the amount to be deposited, mint lp token/ | {
uint256 lpTokenAmount = getMintAmount(bTokenIdx, bTokenAmount);
require(
lpTokenAmount >= lpTokenMintedMin,
"lpToken minted should >= minimum lpToken asked"
);
_transferIn(_tokenInfos[bTokenIdx], bTokenAmount);
_mint(msg.sender, lpTokenAmount);
emit Mint(msg.sender, bTokenAmount, lpTokenAmount);
}
| 523,998 | [
1,
6083,
326,
1147,
612,
471,
326,
3844,
358,
506,
443,
1724,
329,
16,
312,
474,
12423,
1147,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
288,
203,
3639,
2254,
5034,
12423,
1345,
6275,
273,
2108,
474,
6275,
12,
70,
1345,
4223,
16,
324,
1345,
6275,
1769,
203,
3639,
2583,
12,
203,
5411,
12423,
1345,
6275,
1545,
12423,
1345,
49,
474,
329,
2930,
16,
203,
5411,
315,
9953,
1345,
312,
474,
329,
1410,
1545,
5224,
12423,
1345,
19279,
6,
203,
3639,
11272,
203,
203,
3639,
389,
13866,
382,
24899,
2316,
7655,
63,
70,
1345,
4223,
6487,
324,
1345,
6275,
1769,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
12423,
1345,
6275,
1769,
203,
3639,
3626,
490,
474,
12,
3576,
18,
15330,
16,
324,
1345,
6275,
16,
12423,
1345,
6275,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-10-06
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma abicoder v2;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IPopsicleV3Optimizer {
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @return The address of the Uniswap V3 Pool
function pool() external view returns (IUniswapV3Pool);
/// @notice The lower tick of the range
function tickLower() external view returns (int24);
/// @notice The upper tick of the range
function tickUpper() external view returns (int24);
/**
* @notice Deposits tokens in proportion to the Optimizer's current ticks.
* @param amount0Desired Max amount of token0 to deposit
* @param amount1Desired Max amount of token1 to deposit
* @param to address that plp should be transfered
* @return shares minted
* @return amount0 Amount of token0 deposited
* @return amount1 Amount of token1 deposited
*/
function deposit(uint256 amount0Desired, uint256 amount1Desired, address to) external returns (uint256 shares, uint256 amount0,uint256 amount1);
/**
* @notice Withdraws tokens in proportion to the Optimizer's holdings.
* @dev Removes proportional amount of liquidity from Uniswap.
* @param shares burned by sender
* @return amount0 Amount of token0 sent to recipient
* @return amount1 Amount of token1 sent to recipient
*/
function withdraw(uint256 shares, address to) external returns (uint256 amount0, uint256 amount1);
/**
* @notice Updates Optimizer's positions.
* @dev Finds base position and limit position for imbalanced token
* mints all amounts to this position(including earned fees)
*/
function rerange() external;
/**
* @notice Updates Optimizer's positions. Can only be called by the governance.
* @dev Swaps imbalanced token. Finds base position and limit position for imbalanced token if
* we don't have balance during swap because of price impact.
* mints all amounts to this position(including earned fees)
*/
function rebalance() external;
}
interface IOptimizerStrategy {
/// @return Maximul PLP value that could be minted
function maxTotalSupply() external view returns (uint256);
/// @notice Period of time that we observe for price slippage
/// @return time in seconds
function twapDuration() external view returns (uint32);
/// @notice Maximum deviation of time waited avarage price in ticks
function maxTwapDeviation() external view returns (int24);
/// @notice Tick multuplier for base range calculation
function tickRangeMultiplier() external view returns (int24);
/// @notice The price impact percentage during swap denominated in hundredths of a bip, i.e. 1e-6
/// @return The max price impact percentage
function priceImpactPercentage() external view returns (uint24);
}
library PositionKey {
/// @dev Returns the key of the position in the core library
function compute(
address owner,
int24 tickLower,
int24 tickUpper
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(owner, tickLower, tickUpper));
}
}
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
/// @title Liquidity and ticks functions
/// @notice Provides functions for computing liquidity and ticks for token amounts and prices
library PoolVariables {
using LowGasSafeMath for uint256;
using LowGasSafeMath for uint128;
// Cache struct for calculations
struct Info {
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0;
uint256 amount1;
uint128 liquidity;
int24 tickLower;
int24 tickUpper;
}
/// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`.
/// @param pool Uniswap V3 pool
/// @param liquidity The liquidity being valued
/// @param _tickLower The lower tick of the range
/// @param _tickUpper The upper tick of the range
/// @return amounts of token0 and token1 that corresponds to liquidity
function amountsForLiquidity(
IUniswapV3Pool pool,
uint128 liquidity,
int24 _tickLower,
int24 _tickUpper
) internal view returns (uint256, uint256) {
//Get current price from the pool
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(_tickLower),
TickMath.getSqrtRatioAtTick(_tickUpper),
liquidity
);
}
/// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`.
/// @param pool Uniswap V3 pool
/// @param amount0 The amount of token0
/// @param amount1 The amount of token1
/// @param _tickLower The lower tick of the range
/// @param _tickUpper The upper tick of the range
/// @return The maximum amount of liquidity that can be held amount0 and amount1
function liquidityForAmounts(
IUniswapV3Pool pool,
uint256 amount0,
uint256 amount1,
int24 _tickLower,
int24 _tickUpper
) internal view returns (uint128) {
//Get current price from the pool
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(_tickLower),
TickMath.getSqrtRatioAtTick(_tickUpper),
amount0,
amount1
);
}
/// @dev Amounts of token0 and token1 held in contract position.
/// @param pool Uniswap V3 pool
/// @param protocolFees0 protocol fees of token0
/// @param protocolFees1 protocol fees of token1
/// @param protocolFee protocol fee percentage
/// @param divisioner global divisioner
/// @param _tickLower The lower tick of the range
/// @param _tickUpper The upper tick of the range
/// @return amount0 The amount of token0 held in position
/// @return amount1 The amount of token1 held in position
function usersAmounts(IUniswapV3Pool pool, uint256 protocolFees0, uint256 protocolFees1, uint128 protocolFee, uint128 divisioner, int24 _tickLower, int24 _tickUpper)
internal
view
returns (uint256 amount0, uint256 amount1)
{
//Compute position key
bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper);
//Get Position.Info for specified ticks
(uint128 liquidity, , , uint128 tokensOwed0, uint128 tokensOwed1) =
pool.positions(positionKey);
uint128 protocolLiquidity = liquidityForAmounts(pool, protocolFees0, protocolFees1, _tickLower, _tickUpper);
// Calc amounts of token0 and token1 including fees
(amount0, amount1) = amountsForLiquidity(pool, liquidity.sub128(protocolLiquidity), _tickLower, _tickUpper);
uint usersFee0 = tokensOwed0.sub128(tokensOwed0.mul128(protocolFee) / divisioner);
uint usersFee1 = tokensOwed1.sub128(tokensOwed1.mul128(protocolFee) / divisioner);
amount0 = amount0.add(usersFee0);
amount1 = amount1.add(usersFee1);
}
/// @dev Amount of liquidity in contract position.
/// @param pool Uniswap V3 pool
/// @param _tickLower The lower tick of the range
/// @param _tickUpper The upper tick of the range
/// @return liquidity stored in position
function positionLiquidity(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper)
internal
view
returns (uint128 liquidity)
{
//Compute position key
bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper);
//Get liquidity stored in position
(liquidity, , , , ) = pool.positions(positionKey);
}
/// @dev Common checks for valid tick inputs.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
function checkRange(int24 tickLower, int24 tickUpper) internal pure {
require(tickLower < tickUpper, "TLU");
require(tickLower >= TickMath.MIN_TICK, "TLM");
require(tickUpper <= TickMath.MAX_TICK, "TUM");
}
/// @dev Rounds tick down towards negative infinity so that it's a multiple
/// of `tickSpacing`.
function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) {
int24 compressed = tick / tickSpacing;
if (tick < 0 && tick % tickSpacing != 0) compressed--;
return compressed * tickSpacing;
}
/// @dev Gets ticks with proportion equivalent to desired amount
/// @param pool Uniswap V3 pool
/// @param amount0Desired The desired amount of token0
/// @param amount1Desired The desired amount of token1
/// @param baseThreshold The range for upper and lower ticks
/// @param tickSpacing The pool tick spacing
/// @return tickLower The lower tick of the range
/// @return tickUpper The upper tick of the range
function getPositionTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 baseThreshold, int24 tickSpacing) internal view returns(int24 tickLower, int24 tickUpper) {
Info memory cache =
Info(amount0Desired, amount1Desired, 0, 0, 0, 0, 0);
// Get current price and tick from the pool
( uint160 sqrtPriceX96, int24 currentTick, , , , , ) = pool.slot0();
//Calc base ticks
(cache.tickLower, cache.tickUpper) = baseTicks(currentTick, baseThreshold, tickSpacing);
//Calc amounts of token0 and token1 that can be stored in base range
(cache.amount0, cache.amount1) = amountsForTicks(pool, cache.amount0Desired, cache.amount1Desired, cache.tickLower, cache.tickUpper);
//Liquidity that can be stored in base range
cache.liquidity = liquidityForAmounts(pool, cache.amount0, cache.amount1, cache.tickLower, cache.tickUpper);
//Get imbalanced token
bool zeroGreaterOne = amountsDirection(cache.amount0Desired, cache.amount1Desired, cache.amount0, cache.amount1);
//Calc new tick(upper or lower) for imbalanced token
if ( zeroGreaterOne) {
uint160 nextSqrtPrice0 = SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp(sqrtPriceX96, cache.liquidity, cache.amount0Desired, false);
cache.tickUpper = PoolVariables.floor(TickMath.getTickAtSqrtRatio(nextSqrtPrice0), tickSpacing);
}
else{
uint160 nextSqrtPrice1 = SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown(sqrtPriceX96, cache.liquidity, cache.amount1Desired, false);
cache.tickLower = PoolVariables.floor(TickMath.getTickAtSqrtRatio(nextSqrtPrice1), tickSpacing);
}
checkRange(cache.tickLower, cache.tickUpper);
tickLower = cache.tickLower;
tickUpper = cache.tickUpper;
}
/// @dev Gets amounts of token0 and token1 that can be stored in range of upper and lower ticks
/// @param pool Uniswap V3 pool
/// @param amount0Desired The desired amount of token0
/// @param amount1Desired The desired amount of token1
/// @param _tickLower The lower tick of the range
/// @param _tickUpper The upper tick of the range
/// @return amount0 amounts of token0 that can be stored in range
/// @return amount1 amounts of token1 that can be stored in range
function amountsForTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 _tickLower, int24 _tickUpper) internal view returns(uint256 amount0, uint256 amount1) {
uint128 liquidity = liquidityForAmounts(pool, amount0Desired, amount1Desired, _tickLower, _tickUpper);
(amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper);
}
/// @dev Calc base ticks depending on base threshold and tickspacing
function baseTicks(int24 currentTick, int24 baseThreshold, int24 tickSpacing) internal pure returns(int24 tickLower, int24 tickUpper) {
int24 tickFloor = floor(currentTick, tickSpacing);
tickLower = tickFloor - baseThreshold;
tickUpper = tickFloor + baseThreshold;
}
/// @dev Get imbalanced token
/// @param amount0Desired The desired amount of token0
/// @param amount1Desired The desired amount of token1
/// @param amount0 Amounts of token0 that can be stored in base range
/// @param amount1 Amounts of token1 that can be stored in base range
/// @return zeroGreaterOne true if token0 is imbalanced. False if token1 is imbalanced
function amountsDirection(uint256 amount0Desired, uint256 amount1Desired, uint256 amount0, uint256 amount1) internal pure returns (bool zeroGreaterOne) {
zeroGreaterOne = amount0Desired.sub(amount0).mul(amount1Desired) > amount1Desired.sub(amount1).mul(amount0Desired) ? true : false;
}
// Check price has not moved a lot recently. This mitigates price
// manipulation during rebalance and also prevents placing orders
// when it's too volatile.
function checkDeviation(IUniswapV3Pool pool, int24 maxTwapDeviation, uint32 twapDuration) internal view {
(, int24 currentTick, , , , , ) = pool.slot0();
int24 twap = getTwap(pool, twapDuration);
int24 deviation = currentTick > twap ? currentTick - twap : twap - currentTick;
require(deviation <= maxTwapDeviation, "PSC");
}
/// @dev Fetches time-weighted average price in ticks from Uniswap pool for specified duration
function getTwap(IUniswapV3Pool pool, uint32 twapDuration) internal view returns (int24) {
uint32 _twapDuration = twapDuration;
uint32[] memory secondsAgo = new uint32[](2);
secondsAgo[0] = _twapDuration;
secondsAgo[1] = 0;
(int56[] memory tickCumulatives, ) = pool.observe(secondsAgo);
return int24((tickCumulatives[1] - tickCumulatives[0]) / _twapDuration);
}
}
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
}
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
}
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
}
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
}
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions
{
}
/// @title This library is created to conduct a variety of burn liquidity methods
library PoolActions {
using PoolVariables for IUniswapV3Pool;
using LowGasSafeMath for uint256;
using SafeCast for uint256;
/**
* @notice Withdraws liquidity in share proportion to the Optimizer's totalSupply.
* @param pool Uniswap V3 pool
* @param tickLower The lower tick of the range
* @param tickUpper The upper tick of the range
* @param totalSupply The amount of total shares in existence
* @param share to burn
* @param to Recipient of amounts
* @param protocolLiquidity liquidity that corresponds to protocol fees
* @return amount0 Amount of token0 withdrawed
* @return amount1 Amount of token1 withdrawed
*/
function burnLiquidityShare(
IUniswapV3Pool pool,
int24 tickLower,
int24 tickUpper,
uint256 totalSupply,
uint256 share,
address to,
uint128 protocolLiquidity
) internal returns (uint256 amount0, uint256 amount1) {
require(totalSupply > 0, "TS");
uint128 liquidityInPool = pool.positionLiquidity(tickLower, tickUpper);
uint256 liquidity = uint256(liquidityInPool).sub(protocolLiquidity).mul(share) / totalSupply;
if (liquidity > 0) {
(amount0, amount1) = pool.burn(tickLower, tickUpper, liquidity.toUint128());
if (amount0 > 0 || amount1 > 0) {
// collect liquidity share
(amount0, amount1) = pool.collect(
to,
tickLower,
tickUpper,
amount0.toUint128(),
amount1.toUint128()
);
}
}
}
/**
* @notice Withdraws exact amount of liquidity
* @param pool Uniswap V3 pool
* @param tickLower The lower tick of the range
* @param tickUpper The upper tick of the range
* @param liquidity to burn
* @param to Recipient of amounts
* @return amount0 Amount of token0 withdrawed
* @return amount1 Amount of token1 withdrawed
*/
function burnExactLiquidity(
IUniswapV3Pool pool,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address to
) internal returns (uint256 amount0, uint256 amount1) {
uint128 liquidityInPool = pool.positionLiquidity(tickLower, tickUpper);
require(liquidityInPool >= liquidity, "TML");
(amount0, amount1) = pool.burn(tickLower, tickUpper, liquidity);
if (amount0 > 0 || amount1 > 0) {
// collect liquidity share including earned fees
(amount0, amount1) = pool.collect(
to,
tickLower,
tickUpper,
amount0.toUint128(),
amount1.toUint128()
);
}
}
/**
* @notice Withdraws all liquidity in a range from Uniswap pool
* @param pool Uniswap V3 pool
* @param tickLower The lower tick of the range
* @param tickUpper The upper tick of the range
*/
function burnAllLiquidity(
IUniswapV3Pool pool,
int24 tickLower,
int24 tickUpper
) internal {
// Burn all liquidity in this range
uint128 liquidity = pool.positionLiquidity(tickLower, tickUpper);
if (liquidity > 0) {
pool.burn(tickLower, tickUpper, liquidity);
}
// Collect all owed tokens
pool.collect(
address(this),
tickLower,
tickUpper,
type(uint128).max,
type(uint128).max
);
}
}
// 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);
}
}
/**
* @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 {LowGasSafeMAth}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using LowGasSafeMath 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 {LowGasSafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
}
/// @title Function for getting the current chain ID
library ChainId {
/// @dev Gets the current chain ID
/// @return chainId The current chain ID
function get() internal pure returns (uint256 chainId) {
assembly {
chainId := chainid()
}
}
}
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// 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, "ISS");
require(v == 27 || v == 28, "ISV");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "IS");
return signer;
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
/**
* @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].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* 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].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = ChainId.get();
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (ChainId.get() == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) {
return keccak256(
abi.encode(
typeHash,
name,
version,
ChainId.get(),
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 virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
/*
* @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 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 LowGasSafeMath 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_) {
_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, "TEA"));
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, "DEB"));
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), "FZA");
require(recipient != address(0), "TZA");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "TEB");
_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), "MZA");
_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), "BZA");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "BEB");
_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), "AFZA");
require(spender != address(0), "ATZA");
_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 { }
}
/**
* @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.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping (address => Counters.Counter) private _nonces;
//keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private immutable _PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/**
* @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.
*/
constructor(string memory name) EIP712(name, "1") {
}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ED");
bytes32 structHash = keccak256(
abi.encode(
_PERMIT_TYPEHASH,
owner,
spender,
value,
_useNonce(owner),
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "IS");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual 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();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
/// @notice Returns ceil(x / y)
/// @dev division by 0 has unspecified behavior, and must be checked externally
/// @param x The dividend
/// @param y The divisor
/// @return z The quotient, ceil(x / y)
function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
/// @notice Returns floor(x / y)
/// @dev division by 0 has unspecified behavior, and must be checked externally
/// @param x The dividend
/// @param y The divisor
/// @return z The quotient, floor(x / y)
function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
z := div(x, y)
}
}
}
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint128
function toUint128(uint256 y) internal pure returns (uint128 z) {
require((z = uint128(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int256 y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = int256(y);
}
}
/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y, string memory errorMessage) internal pure returns (uint256 z) {
require((z = x - y) <= x, errorMessage);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
/// @notice Returns x + y, reverts if sum overflows uint128
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add128(uint128 x, uint128 y) internal pure returns (uint128 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub128(uint128 x, uint128 y) internal pure returns (uint128 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul128(uint128 x, uint128 y) internal pure returns (uint128 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if sum overflows uint128
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add160(uint160 x, uint160 y) internal pure returns (uint160 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub160(uint160 x, uint160 y) internal pure returns (uint160 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul160(uint160 x, uint160 y) internal pure returns (uint160 z) {
require(x == 0 || (z = x * y) / x == y);
}
}
/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath {
using LowGasSafeMath for uint256;
using SafeCast for uint256;
/// @notice Gets the next sqrt price given a delta of token0
/// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
/// price less in order to not send too much output.
/// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
/// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
/// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of token0 to add or remove from virtual reserves
/// @param add Whether to add or remove the amount of token0
/// @return The price after adding or removing amount, depending on add
function getNextSqrtPriceFromAmount0RoundingUp(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amount,
bool add
) internal pure returns (uint160) {
// we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
if (amount == 0) return sqrtPX96;
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
if (add) {
uint256 product;
if ((product = amount * sqrtPX96) / amount == sqrtPX96) {
uint256 denominator = numerator1 + product;
if (denominator >= numerator1)
// always fits in 160 bits
return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
}
return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));
} else {
uint256 product;
// if the product overflows, we know the denominator underflows
// in addition, we must check that the denominator does not underflow
require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);
uint256 denominator = numerator1 - product;
return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
}
}
/// @notice Gets the next sqrt price given a delta of token1
/// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
/// price less in order to not send too much output.
/// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
/// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of token1 to add, or remove, from virtual reserves
/// @param add Whether to add, or remove, the amount of token1
/// @return The price after adding or removing `amount`
function getNextSqrtPriceFromAmount1RoundingDown(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amount,
bool add
) internal pure returns (uint160) {
// if we're adding (subtracting), rounding down requires rounding the quotient down (up)
// in both cases, avoid a mulDiv for most inputs
if (add) {
uint256 quotient =
(
amount <= type(uint160).max
? (amount << FixedPoint96.RESOLUTION) / liquidity
: FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
);
return uint256(sqrtPX96).add(quotient).toUint160();
} else {
uint256 quotient =
(
amount <= type(uint160).max
? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
: FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
);
require(sqrtPX96 > quotient);
// always fits 160 bits
return uint160(sqrtPX96 - quotient);
}
}
}
library TransferHelper {
/// @notice Transfers tokens from the targeted address to the given destination
/// @notice Errors with 'STF' if transfer fails
/// @param token The contract address of the token to be transferred
/// @param from The originating address from which the tokens will be transferred
/// @param to The destination address of the transfer
/// @param value The amount to be transferred
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
}
/// @notice Transfers tokens from msg.sender to a recipient
/// @dev Errors with ST if transfer fails
/// @param token The contract address of the token which will be transferred
/// @param to The recipient of the transfer
/// @param value The value of the transfer
function safeTransfer(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "RC");
// 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;
}
}
/// @title Interface for WETH9
interface IWETH9 is IERC20 {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
}
/// @title PopsicleV3 Optimizer is a yield enchancement v3 contract
/// @dev PopsicleV3 Optimizer is a Uniswap V3 yield enchancement contract which acts as
/// intermediary between the user who wants to provide liquidity to specific pools
/// and earn fees from such actions. The contract ensures that user position is in
/// range and earns maximum amount of fees available at current liquidity utilization
/// rate.
contract PopsicleV3Optimizer is ERC20Permit, ReentrancyGuard, IPopsicleV3Optimizer {
using LowGasSafeMath for uint256;
using LowGasSafeMath for uint160;
using LowGasSafeMath for uint128;
using UnsafeMath for uint256;
using SafeCast for uint256;
using PoolVariables for IUniswapV3Pool;
using PoolActions for IUniswapV3Pool;
//Any data passed through by the caller via the IUniswapV3PoolActions#mint call
struct MintCallbackData {
address payer;
}
//Any data passed through by the caller via the IUniswapV3PoolActions#swap call
struct SwapCallbackData {
bool zeroForOne;
}
/// @notice Emitted when user adds liquidity
/// @param sender The address that minted the liquidity
/// @param share The amount of share of liquidity added by the user to position
/// @param amount0 How much token0 was required for the added liquidity
/// @param amount1 How much token1 was required for the added liquidity
event Deposit(
address indexed sender,
uint256 share,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when user withdraws liquidity
/// @param sender The address that minted the liquidity
/// @param shares of liquidity withdrawn by the user from the position
/// @param amount0 How much token0 was required for the added liquidity
/// @param amount1 How much token1 was required for the added liquidity
event Withdraw(
address indexed sender,
uint256 shares,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees was collected from the pool
/// @param feesFromPool0 Total amount of fees collected in terms of token 0
/// @param feesFromPool1 Total amount of fees collected in terms of token 1
/// @param usersFees0 Total amount of fees collected by users in terms of token 0
/// @param usersFees1 Total amount of fees collected by users in terms of token 1
event CollectFees(
uint256 feesFromPool0,
uint256 feesFromPool1,
uint256 usersFees0,
uint256 usersFees1
);
/// @notice Emitted when fees was compuonded to the pool
/// @param amount0 Total amount of fees compounded in terms of token 0
/// @param amount1 Total amount of fees compounded in terms of token 1
event CompoundFees(
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when PopsicleV3 Optimizer changes the position in the pool
/// @param tickLower Lower price tick of the positon
/// @param tickUpper Upper price tick of the position
/// @param amount0 Amount of token 0 deposited to the position
/// @param amount1 Amount of token 1 deposited to the position
event Rerange(
int24 tickLower,
int24 tickUpper,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when user collects his fee share
/// @param sender User address
/// @param fees0 Exact amount of fees claimed by the users in terms of token 0
/// @param fees1 Exact amount of fees claimed by the users in terms of token 1
event RewardPaid(
address indexed sender,
uint256 fees0,
uint256 fees1
);
/// @notice Shows current Optimizer's balances
/// @param totalAmount0 Current token0 Optimizer's balance
/// @param totalAmount1 Current token1 Optimizer's balance
event Snapshot(uint256 totalAmount0, uint256 totalAmount1);
event TransferGovernance(address indexed previousGovernance, address indexed newGovernance);
/// @notice Prevents calls from users
modifier onlyGovernance {
require(msg.sender == governance, "OG");
_;
}
/// @inheritdoc IPopsicleV3Optimizer
address public immutable override token0;
/// @inheritdoc IPopsicleV3Optimizer
address public immutable override token1;
// WETH address
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// @inheritdoc IPopsicleV3Optimizer
int24 public immutable override tickSpacing;
uint constant MULTIPLIER = 1e6;
uint24 constant GLOBAL_DIVISIONER = 1e6; // for basis point (0.0001%)
//The protocol's fee in hundredths of a bip, i.e. 1e-6
uint24 constant protocolFee = 1e5;
mapping (address => bool) private _operatorApproved;
// @inheritdoc IPopsicleV3Optimizer
IUniswapV3Pool public override pool;
// Accrued protocol fees in terms of token0
uint256 public protocolFees0;
// Accrued protocol fees in terms of token1
uint256 public protocolFees1;
// Total lifetime accrued fees in terms of token0
uint256 public totalFees0;
// Total lifetime accrued fees in terms of token1
uint256 public totalFees1;
// Address of the Optimizer's owner
address public governance;
// Pending to claim ownership address
address public pendingGovernance;
//PopsicleV3 Optimizer settings address
address public strategy;
// Current tick lower of Optimizer pool position
int24 public override tickLower;
// Current tick higher of Optimizer pool position
int24 public override tickUpper;
// Checks if Optimizer is initialized
bool public initialized;
bool private _paused = false;
/**
* @dev After deploying, strategy can be set via `setStrategy()`
* @param _pool Underlying Uniswap V3 pool with fee = 3000
* @param _strategy Underlying Optimizer Strategy for Optimizer settings
*/
constructor(
address _pool,
address _strategy
) ERC20("Popsicle LP V3 USDT/WETH", "PLP") ERC20Permit("Popsicle LP V3 USDT/WETH") {
pool = IUniswapV3Pool(_pool);
strategy = _strategy;
token0 = pool.token0();
token1 = pool.token1();
tickSpacing = pool.tickSpacing();
governance = msg.sender;
_operatorApproved[msg.sender] = true;
}
//initialize strategy
function init() external onlyGovernance {
require(!initialized, "F");
initialized = true;
int24 baseThreshold = tickSpacing * IOptimizerStrategy(strategy).tickRangeMultiplier();
( , int24 currentTick, , , , , ) = pool.slot0();
int24 tickFloor = PoolVariables.floor(currentTick, tickSpacing);
tickLower = tickFloor - baseThreshold;
tickUpper = tickFloor + baseThreshold;
PoolVariables.checkRange(tickLower, tickUpper); //check ticks also for overflow/underflow
}
/// @inheritdoc IPopsicleV3Optimizer
function deposit(
uint256 amount0Desired,
uint256 amount1Desired,
address to
)
external
override
nonReentrant
checkDeviation
whenNotPaused
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
)
{
require(amount0Desired > 0 && amount1Desired > 0, "ANV");
_earnFees();
_compoundFees(); // prevent user drains others
uint128 protocolLiquidity = pool.liquidityForAmounts(protocolFees0, protocolFees1, tickLower, tickUpper);
uint128 liquidityLast = pool.positionLiquidity(tickLower, tickUpper).sub128(protocolLiquidity); // prevent protocol drains users
// compute the liquidity amount
uint128 liquidity = pool.liquidityForAmounts(amount0Desired, amount1Desired, tickLower, tickUpper);
(amount0, amount1) = pool.mint(
address(this),
tickLower,
tickUpper,
liquidity,
abi.encode(MintCallbackData({payer: msg.sender})));
shares = _calcShare(liquidity*MULTIPLIER, liquidityLast*MULTIPLIER);
_mint(to, shares);
require(IOptimizerStrategy(strategy).maxTotalSupply() >= totalSupply(), "MTS");
emit Deposit(msg.sender, shares, amount0, amount1);
}
/// @inheritdoc IPopsicleV3Optimizer
function withdraw(
uint256 shares,
address to
)
external
override
nonReentrant
checkDeviation
whenNotPaused
returns (
uint256 amount0,
uint256 amount1
)
{
require(shares > 0, "S");
require(to != address(0), "WZA");
_earnFees();
_compoundFees();
//Get Liquidity for ProtocolFee
uint128 protocolLiquidity = pool.liquidityForAmounts(protocolFees0, protocolFees1, tickLower, tickUpper);
(amount0, amount1) = pool.burnLiquidityShare(tickLower, tickUpper, totalSupply(), shares, to, protocolLiquidity);
// Burn shares
_burn(msg.sender, shares);
emit Withdraw(msg.sender, shares, amount0, amount1);
}
/// @inheritdoc IPopsicleV3Optimizer
function rerange() external override nonReentrant checkDeviation {
require(_operatorApproved[msg.sender], "ONA");
_earnFees();
//Burn all liquidity from pool to rerange for Optimizer's balances.
pool.burnAllLiquidity(tickLower, tickUpper);
// Emit snapshot to record balances
uint256 balance0 = _balance0();
uint256 balance1 = _balance1();
emit Snapshot(balance0, balance1);
int24 baseThreshold = tickSpacing * IOptimizerStrategy(strategy).tickRangeMultiplier();
//Get exact ticks depending on Optimizer's balances
(tickLower, tickUpper) = pool.getPositionTicks(balance0, balance1, baseThreshold, tickSpacing);
//Get Liquidity for Optimizer's balances
uint128 liquidity = pool.liquidityForAmounts(balance0, balance1, tickLower, tickUpper);
// Add liquidity to the pool
(uint256 amount0, uint256 amount1) = pool.mint(
address(this),
tickLower,
tickUpper,
liquidity,
abi.encode(MintCallbackData({payer: address(this)})));
emit Rerange(tickLower, tickUpper, amount0, amount1);
}
/// @inheritdoc IPopsicleV3Optimizer
function rebalance() external override nonReentrant checkDeviation {
require(_operatorApproved[msg.sender], "ONA");
_earnFees();
//Burn all liquidity from pool to rerange for Optimizer's balances.
pool.burnAllLiquidity(tickLower, tickUpper);
//Calc base ticks
(uint160 sqrtPriceX96, int24 currentTick, , , , , ) = pool.slot0();
PoolVariables.Info memory cache;
int24 baseThreshold = tickSpacing * IOptimizerStrategy(strategy).tickRangeMultiplier();
(cache.tickLower, cache.tickUpper) = PoolVariables.baseTicks(currentTick, baseThreshold, tickSpacing);
cache.amount0Desired = _balance0();
cache.amount1Desired = _balance1();
emit Snapshot(cache.amount0Desired, cache.amount1Desired);
// Calc liquidity for base ticks
cache.liquidity = pool.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, cache.tickLower, cache.tickUpper);
// Get exact amounts for base ticks
(cache.amount0, cache.amount1) = pool.amountsForLiquidity(cache.liquidity, cache.tickLower, cache.tickUpper);
// Get imbalanced token
bool zeroForOne = PoolVariables.amountsDirection(cache.amount0Desired, cache.amount1Desired, cache.amount0, cache.amount1);
// Calculate the amount of imbalanced token that should be swapped. Calculations strive to achieve one to one ratio
int256 amountSpecified =
zeroForOne
? int256(cache.amount0Desired.sub(cache.amount0).unsafeDiv(2))
: int256(cache.amount1Desired.sub(cache.amount1).unsafeDiv(2)); // always positive. "overflow" safe convertion cuz we are dividing by 2
// Calculate Price limit depending on price impact
uint160 exactSqrtPriceImpact = sqrtPriceX96.mul160(IOptimizerStrategy(strategy).priceImpactPercentage() / 2) / GLOBAL_DIVISIONER;
uint160 sqrtPriceLimitX96 = zeroForOne ? sqrtPriceX96.sub160(exactSqrtPriceImpact) : sqrtPriceX96.add160(exactSqrtPriceImpact);
//Swap imbalanced token as long as we haven't used the entire amountSpecified and haven't reached the price limit
pool.swap(
address(this),
zeroForOne,
amountSpecified,
sqrtPriceLimitX96,
abi.encode(SwapCallbackData({zeroForOne: zeroForOne}))
);
(sqrtPriceX96, currentTick, , , , , ) = pool.slot0();
// Emit snapshot to record balances
cache.amount0Desired = _balance0();
cache.amount1Desired = _balance1();
emit Snapshot(cache.amount0Desired, cache.amount1Desired);
//Get exact ticks depending on Optimizer's new balances
(tickLower, tickUpper) = pool.getPositionTicks(cache.amount0Desired, cache.amount1Desired, baseThreshold, tickSpacing);
cache.liquidity = pool.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, tickLower, tickUpper);
// Add liquidity to the pool
(cache.amount0, cache.amount1) = pool.mint(
address(this),
tickLower,
tickUpper,
cache.liquidity,
abi.encode(MintCallbackData({payer: address(this)})));
emit Rerange(tickLower, tickUpper, cache.amount0, cache.amount1);
}
// Calcs user share depending on deposited amounts
function _calcShare(uint256 liquidity, uint256 liquidityLast)
internal
view
returns (
uint256 shares
)
{
shares = totalSupply() == 0 ? liquidity : liquidity.mul(totalSupply()).unsafeDiv(liquidityLast);
}
/// @dev Amount of token0 held as unused balance.
function _balance0() internal view returns (uint256) {
return IERC20(token0).balanceOf(address(this));
}
/// @dev Amount of token1 held as unused balance.
function _balance1() internal view returns (uint256) {
return IERC20(token1).balanceOf(address(this));
}
/// @dev collects fees from the pool
function _earnFees() internal {
uint liquidity = pool.positionLiquidity(tickLower, tickUpper);
if (liquidity == 0) return; // we can't poke when liquidity is zero
// Do zero-burns to poke the Uniswap pools so earned fees are updated
pool.burn(tickLower, tickUpper, 0);
(uint256 collect0, uint256 collect1) =
pool.collect(
address(this),
tickLower,
tickUpper,
type(uint128).max,
type(uint128).max
);
// Calculate protocol's fees
uint256 earnedProtocolFees0 = collect0.mul(protocolFee).unsafeDiv(GLOBAL_DIVISIONER);
uint256 earnedProtocolFees1 = collect1.mul(protocolFee).unsafeDiv(GLOBAL_DIVISIONER);
protocolFees0 = protocolFees0.add(earnedProtocolFees0);
protocolFees1 = protocolFees1.add(earnedProtocolFees1);
totalFees0 = totalFees0.add(collect0);
totalFees1 = totalFees1.add(collect1);
emit CollectFees(collect0, collect1, totalFees0, totalFees1);
}
function _compoundFees() internal returns (uint256 amount0, uint256 amount1){
uint256 balance0 = _balance0();
uint256 balance1 = _balance1();
emit Snapshot(balance0, balance1);
//Get Liquidity for Optimizer's balances
uint128 liquidity = pool.liquidityForAmounts(balance0, balance1, tickLower, tickUpper);
// Add liquidity to the pool
if (liquidity > 0)
{
(amount0, amount1) = pool.mint(
address(this),
tickLower,
tickUpper,
liquidity,
abi.encode(MintCallbackData({payer: address(this)})));
emit CompoundFees(amount0, amount1);
}
}
/// @notice Returns current Optimizer's position in pool
function position() external view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1) {
bytes32 positionKey = PositionKey.compute(address(this), tickLower, tickUpper);
(liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = pool.positions(positionKey);
}
/// @notice Returns current Optimizer's users amounts in pool
function usersAmounts() external view returns (uint256 amount0, uint256 amount1) {
(amount0, amount1) = pool.usersAmounts(protocolFees0, protocolFees1, protocolFee, GLOBAL_DIVISIONER, tickLower, tickUpper);
}
/// @notice Pull in tokens from sender. Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
/// @dev In the implementation you must pay to the pool for the minted liquidity.
/// @param amount0 The amount of token0 due to the pool for the minted liquidity
/// @param amount1 The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata data
) external {
require(msg.sender == address(pool), "FP");
MintCallbackData memory decoded = abi.decode(data, (MintCallbackData));
if (amount0 > 0) pay(token0, decoded.payer, msg.sender, amount0);
if (amount1 > 0) pay(token1, decoded.payer, msg.sender, amount1);
}
/// @notice Called to `msg.sender` after minting swaping from IUniswapV3Pool#swap.
/// @dev In the implementation you must pay to the pool for swap.
/// @param amount0 The amount of token0 due to the pool for the swap
/// @param amount1 The amount of token1 due to the pool for the swap
/// @param _data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0,
int256 amount1,
bytes calldata _data
) external {
require(msg.sender == address(pool), "FP");
require(amount0 > 0 || amount1 > 0, "LEZ"); // swaps entirely within 0-liquidity regions are not supported
SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData));
bool zeroForOne = data.zeroForOne;
if (zeroForOne) pay(token0, address(this), msg.sender, uint256(amount0));
else pay(token1, address(this), msg.sender, uint256(amount1));
}
/// @param token The token to pay
/// @param payer The entity that must pay
/// @param recipient The entity that will receive payment
/// @param value The amount to pay
function pay(
address token,
address payer,
address recipient,
uint256 value
) internal {
if (token == weth && address(this).balance >= value) {
// pay with WETH9
IWETH9(weth).deposit{value: value}(); // wrap only what is needed to pay
IWETH9(weth).transfer(recipient, value);
} else if (payer == address(this)) {
// pay with tokens already in the contract (for the exact input multihop case)
TransferHelper.safeTransfer(token, recipient, value);
} else {
// pull payment
TransferHelper.safeTransferFrom(token, payer, recipient, value);
}
}
/**
* @notice Used to withdraw accumulated protocol fees.
*/
function collectProtocolFees(
uint256 amount0,
uint256 amount1
) external nonReentrant onlyGovernance {
_earnFees();
require(protocolFees0 >= amount0, "A0F");
require(protocolFees1 >= amount1, "A1F");
uint256 balance0 = _balance0();
uint256 balance1 = _balance1();
if (balance0 >= amount0 && balance1 >= amount1)
{
if (amount0 > 0) pay(token0, address(this), msg.sender, amount0);
if (amount1 > 0) pay(token1, address(this), msg.sender, amount1);
}
else
{
uint128 liquidity = pool.liquidityForAmounts(amount0, amount1, tickLower, tickUpper);
(amount0, amount1) = pool.burnExactLiquidity(tickLower, tickUpper, liquidity, msg.sender);
}
protocolFees0 = protocolFees0.sub(amount0);
protocolFees1 = protocolFees1.sub(amount1);
_compoundFees();
emit RewardPaid(msg.sender, amount0, amount1);
}
// Function modifier that checks if price has not moved a lot recently.
// This mitigates price manipulation during rebalance and also prevents placing orders
// when it's too volatile.
modifier checkDeviation() {
pool.checkDeviation(IOptimizerStrategy(strategy).maxTwapDeviation(), IOptimizerStrategy(strategy).twapDuration());
_;
}
/**
* @notice `setGovernance()` should be called by the existing governance
* address prior to calling this function.
*/
function setGovernance(address _governance) external onlyGovernance {
pendingGovernance = _governance;
}
/**
* @notice Governance address is not updated until the new governance
* address has called `acceptGovernance()` to accept this responsibility.
*/
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "PG");
emit TransferGovernance(governance, pendingGovernance);
pendingGovernance = address(0);
governance = msg.sender;
}
// Sets new strategy contract address for new settings
function setStrategy(address _strategy) external onlyGovernance {
require(_strategy != address(0), "NA");
strategy = _strategy;
}
function approveOperator(address _operator) external onlyGovernance {
_operatorApproved[_operator] = true;
}
function disableOperator(address _operator) external onlyGovernance {
_operatorApproved[_operator] = false;
}
function isOperator(address _operator) external view returns (bool) {
return _operatorApproved[_operator];
}
/**
* @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, "P");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "NP");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function pause() external onlyGovernance whenNotPaused {
_paused = true;
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function unpause() external onlyGovernance whenPaused {
_paused = false;
}
} | * @notice Used to withdraw accumulated protocol fees./ | function collectProtocolFees(
uint256 amount0,
uint256 amount1
) external nonReentrant onlyGovernance {
_earnFees();
require(protocolFees0 >= amount0, "A0F");
require(protocolFees1 >= amount1, "A1F");
uint256 balance0 = _balance0();
uint256 balance1 = _balance1();
if (balance0 >= amount0 && balance1 >= amount1)
{
if (amount0 > 0) pay(token0, address(this), msg.sender, amount0);
if (amount1 > 0) pay(token1, address(this), msg.sender, amount1);
}
else
{
uint128 liquidity = pool.liquidityForAmounts(amount0, amount1, tickLower, tickUpper);
(amount0, amount1) = pool.burnExactLiquidity(tickLower, tickUpper, liquidity, msg.sender);
}
protocolFees0 = protocolFees0.sub(amount0);
protocolFees1 = protocolFees1.sub(amount1);
_compoundFees();
emit RewardPaid(msg.sender, amount0, amount1);
}
| 10,986,411 | [
1,
6668,
358,
598,
9446,
24893,
1771,
1656,
281,
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,
3274,
5752,
2954,
281,
12,
203,
3639,
2254,
5034,
3844,
20,
16,
203,
3639,
2254,
5034,
3844,
21,
203,
565,
262,
3903,
1661,
426,
8230,
970,
1338,
43,
1643,
82,
1359,
288,
203,
3639,
389,
73,
1303,
2954,
281,
5621,
203,
3639,
2583,
12,
8373,
2954,
281,
20,
1545,
3844,
20,
16,
315,
37,
20,
42,
8863,
203,
3639,
2583,
12,
8373,
2954,
281,
21,
1545,
3844,
21,
16,
315,
37,
21,
42,
8863,
203,
3639,
2254,
5034,
11013,
20,
273,
389,
12296,
20,
5621,
203,
3639,
2254,
5034,
11013,
21,
273,
389,
12296,
21,
5621,
203,
540,
203,
3639,
309,
261,
12296,
20,
1545,
3844,
20,
597,
11013,
21,
1545,
3844,
21,
13,
203,
3639,
288,
203,
5411,
309,
261,
8949,
20,
405,
374,
13,
8843,
12,
2316,
20,
16,
1758,
12,
2211,
3631,
1234,
18,
15330,
16,
3844,
20,
1769,
203,
5411,
309,
261,
8949,
21,
405,
374,
13,
8843,
12,
2316,
21,
16,
1758,
12,
2211,
3631,
1234,
18,
15330,
16,
3844,
21,
1769,
203,
3639,
289,
203,
3639,
469,
203,
3639,
288,
203,
5411,
2254,
10392,
4501,
372,
24237,
273,
2845,
18,
549,
372,
24237,
1290,
6275,
87,
12,
8949,
20,
16,
3844,
21,
16,
4024,
4070,
16,
4024,
5988,
1769,
203,
5411,
261,
8949,
20,
16,
3844,
21,
13,
273,
2845,
18,
70,
321,
14332,
48,
18988,
24237,
12,
6470,
4070,
16,
4024,
5988,
16,
4501,
372,
24237,
16,
1234,
18,
15330,
1769,
203,
540,
203,
3639,
289,
203,
540,
203,
3639,
1771,
2954,
281,
20,
273,
2
]
|
wordentry_set Verbs_Linking_IN =
{
eng_verb:mount{}, // She mounted her guns in five turrets;
eng_verb:occur{},
eng_verb:embed{}, // Sesamoid bones are bones embedded in tendons.
eng_verb:pay{}, // Workers were paid in grain;
eng_verb:welter{}, // The shipwrecked survivors weltered in the sea for hours.
eng_verb:propagate{}, // Sound and light propagate in this medium.
eng_verb:cover{}, // Quantification in general is covered in the article on quantification.
eng_verb:freeze{}, // The water froze in the pond last night
eng_verb:fidget{}, // The child is always fidgeting in his seat.
eng_verb:swirl{}, // The leaves swirled in the autumn wind.
eng_verb:whirl{}, // Rising smoke whirled in the air.
eng_verb:tumble{}, // The clothes tumbled in the dryer.
eng_verb:circulate{}, // Blood circulates in my veins.
eng_verb:concentrate{}, // These groups concentrate in the inner cities.
eng_verb:scatter{}, // The children scattered in all directions when the teacher approached.
eng_verb:pullulate{}, // Beggars pullulated in the plaza.
eng_verb:bunch{}, // The frightened children bunched together in the corner of the classroom.
eng_verb:constellate{}, // The poets constellate in this town every summer.
eng_verb:roll{}, // He rolled up in a black Mercedes.
eng_verb:interpret{}, // In reality these terms have been interpreted in a number of different ways.
eng_verb:continue{}, // She continued in the direction of the hills.
eng_verb:rise{}, // The dough rose slowly in the warm room.
eng_verb:land{}, // The plane landed in Istanbul.
eng_verb:crash{}, // The plane crashed in the sea.
eng_verb:galumph{}, // The giant tortoises galumphed around in their pen.
eng_verb:prance{}, // The young horse was prancing in the meadow.
eng_verb:recommit{}, // The bill was recommitted three times in the House.
eng_verb:interfere{}, // They had an agreement that they would not interfere in each other's business.
eng_verb:busk{}, // Three young men were busking in the plaza.
eng_verb:cruise{}, // We were cruising in the Caribbean.
eng_verb:kite{}, // Kids were kiting in the park.
eng_verb:stomp{}, // The men stomped through the snow in their heavy boots.
eng_verb:stagger{}, // He staggered along in the heavy snow.
eng_verb:plod{}, // Mules plodded in a circle around a grindstone.
eng_verb:hike{}, // We were hiking in Colorado.
eng_verb:puddle{}, // The ducks and geese puddled in the backyard.
eng_verb:blow{}, // The leaves were blowing in the wind.
eng_verb:shift{}, // He shifted in his seat.
eng_verb:whip{}, // The tall grass whipped in the wind.
eng_verb:trash{}, // The feverish patient thrashed around in his bed.
eng_verb:slip{}, // The ship slipped away in the darkness.
eng_verb:churn{}, // The sea was churning in the storm.
eng_verb:romp{}, // The toddlers romped in the playroom.
eng_verb:frolick{}, // The children frolicked in the garden.
eng_verb:flap{}, // Flags flapped in the strong wind.
eng_verb:nod{}, // The flowers were nodding in the breeze.
eng_verb:jostle{}, // The passengers jostled each other in the overcrowded train.
eng_verb:skid{}, // The car skidded in the curve on the wet road.
eng_verb:stall{}, // The car stalled in the driveway.
eng_verb:bring{}, // The noise brought her up in shock.
eng_verb:migrate{}, // Birds migrate in the Winter.
eng_verb:crack{}, // Ribs crack in your ears with sudden unaccustomed flexion.
eng_verb:inflate{}, // The body inflates in painful increments
eng_verb:wallow{}, // Pigs were wallowing in the mud.
eng_verb:bog{}, // The car bogged down in the sand.
eng_verb:appear{}, // A titillating story appeared in the usually conservative magazine.
eng_verb:draw{}, // The deed was drawn in the lawyer's office.
eng_verb:paragraph{}, // All her friends were paragraphed in last Monday's paper.
eng_verb:set{}, // The film is set in Africa.
eng_verb:criticise{}, // He humiliated his colleague by criticising him in front of the boss.
eng_verb:fail{}, // His children failed him in the crisis.
eng_verb:bob{}, // The cork bobbed around in the pool.
eng_verb:writhe{}, // The prisoner writhed in discomfort.
eng_verb:fictionalize{}, // The writer fictionalized the lives of his parents in his latest novel.
eng_verb:clothe{}, // The mountain was clothed in tropical trees.
eng_verb:close{}, // They closed in the porch with a fence.
eng_verb:fence{}, // We fenced in our yard.
eng_verb:clap{}, // The judge clapped him in jail.
eng_verb:remain{}, // She remained stubbornly in the same position.
eng_verb:bathe{}, // The room was bathed in sunlight.
eng_verb:shroud{}, // The origins of this civilization are shrouded in mystery.
eng_verb:soak{}, // I soaked in the hot tub for an hour.
eng_verb:Immerse{}, // Immerse yourself in hot water.
eng_verb:bask{}, // The seals were basking in the sun.
eng_verb:live{},
eng_verb:stay{},
eng_verb:sleep{},
eng_verb:rest{},
eng_verb:perch{}, // The birds perched high in the tree.
eng_verb:wash{}, // Wash out your dirty shirt in the sink.
eng_verb:sandwich{}, // She was sandwiched in her airplane seat between two fat men.
eng_verb:bury{}, // He finally could free the legs of the earthquake victim who was buried in the rubble.
eng_verb:speak{}, // She spoke in a calm voice.
eng_verb:rule{}, // Order ruled in the streets.
eng_verb:leave{}, // His brother's success left him in the shade.
eng_verb:trap{}, // He was trapped in a medical swamp.
eng_verb:result{}, // A continuous rearrangement of electrons in the solar atoms results in the emission of light.
eng_verb:behave{}, // He behaved badly in school.
eng_verb:support{}, // We support the armed services in the name of national security.
eng_verb:use{}, // This type of border display is used repetitively in advertising.
eng_verb:survive{}, // His works tenuously survive in the minds of a few scholars.
eng_verb:sum{}, // The history is summed up concisely in this book.
eng_verb:interest{}, // He is interested specifically in poisonous snakes.
eng_verb:engage{}, // They were busily engaged in buying souvenirs.
eng_verb:display{}, // The new car was prominently displayed in the driveway.
eng_verb:lock{}, // Her jewels are locked away in a safe.
eng_verb:save{}, // She was saved in the nick of time.
eng_verb:accumulate{}, // Journals are accumulating in my office.
eng_verb:geminate{}, // The consonants are geminated in these words.
eng_verb:emend{}, // The text was emended in the second edition.
eng_verb:carry{}, // The civil war carried into the neighboring province.
eng_verb:deepen{}, // His dislike for raw fish only deepened in Japan.
eng_verb:dry{}, // The laundry dries in the sun.
eng_verb:mold{}, // The furniture molded in the old house.
eng_verb:decompose{}, // The bodies decomposed in the heat.
eng_verb:ripen{}, // The plums ripen in July.
eng_verb:grow{}, // He grows vegetables in his backyard.
eng_verb:suffer{}, // This author really suffers in translation.
eng_verb:bulk{}, // The parcel bulked in the sack.
eng_verb:shrink{}, // Proof the materials against shrinking in the dryer.
eng_verb:culminate{}, // The helmet culminated in a crest.
eng_verb:disperse{}, // Particles were colloidally dispersed in the medium.
eng_verb:walk{}, // She walked briskly in the cold air.
eng_verb:act{}, // The admiral intends to act offensively in the Mediterranean.
eng_verb:rustle{}, // The leaves rustled tremulously in the wind.
eng_verb:indulge{}, // He wishfully indulged in dreams of fame.
eng_verb:catch{}, // His hair was caught aggravatingly in the branches of the tree.
eng_verb:go{}, // Something has gone awry in our plans.
eng_verb:toss{}, // Fretfully, the baby tossed in his crib.
eng_verb:fall{}, // He fell headlong in love with his cousin.
eng_verb:believe{}, // His followers slavishly believed in his new diet.
eng_verb:scratch{}, // A single chicken was scratching forlornly in the yard.
eng_verb:involve{}, // Don't involve me in your family affairs!
eng_verb:Dredge{}, // Dredge the chicken in flour before frying it.
eng_verb:publish{}, // It wasn't published in a refereed journal.
eng_verb:chase{}, // I chased the rabbits in the field
eng_verb:see{}, // I saw myself in the mirror
eng_verb:meddle{}, // Don't meddle in my affairs!
eng_verb:drag{}, // Don't drag me into this business.
eng_verb:get{},
eng_verb:roar{}, // The rushing wind roared in our ears
eng_verb:run{}, // I am running in the field
eng_verb:find{}, // One of the most toxic substances is found in this place
eng_verb:execute{}, // all orders are executed in succession
eng_verb:assemble{}, // At nine o'clock, we all assembled in the hall
eng_verb:place{}, // George and I were placed in the same class.
eng_verb:gather{}, // A large number of people gathered in the square.
eng_verb:sing{}, // The bird is singing in the tree
eng_verb:work{}, // Mary does not work in an office
eng_verb:sink{}, // The ship sank in the great storm
eng_verb:destroy{}, // The car was totally destroyed in the crash
eng_verb:play{}, // The boys are playing in the field
eng_verb:bake{}, // It had been baked in a big oven
eng_verb:fix{}, // This issue has been fixed in the source repository.
eng_verb:swim{}, // Richard and Henry swam in the river
eng_verb:print{}, // This book was printed in London
eng_verb:listen{}, // The audience listened in breathless silence to the singer
eng_verb:stand{}, // They stood in the rain for an hour
eng_verb:meet{}, // Meet me in the same place
eng_verb:keep{}, // The teacher knew how to keep the class in line.
eng_verb:outmaneuver{}, // My new supervisor knows how to outmaneuver the boss in most situations.
eng_verb:hammer{}, // Hammer the nails in well
eng_verb:dig{}, // He's been digging in the garden all morning
eng_verb:teach{}, // The teacher is teaching in this school now
eng_verb:hang{}, // The astronaut hung weightlessly in the capsule
eng_verb:water{}, // You should water them every day in dry weather
eng_verb:sit{} // She sat in the corner
}
| The bodies decomposed in the heat.
| eng_verb:decompose{}, | 899,811 | [
1,
1986,
25126,
9862,
7423,
316,
326,
19347,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
24691,
67,
16629,
30,
323,
23658,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
/**
* @title HidingVault's state management library
* @author KeeperDAO
* @dev Library that manages the state of the HidingVault
*/
library LibHidingVault {
// HIDING_VAULT_STORAGE_POSITION = keccak256("hiding-vault.keeperdao.storage")
bytes32 constant HIDING_VAULT_STORAGE_POSITION = 0x9b85f6ce841a6faee042a2e67df9613579f746ca80e5eb1163b287041381d23c;
struct State {
NFTLike nft;
mapping(address => bool) recoverableTokensBlacklist;
}
function state() internal pure returns (State storage s) {
bytes32 position = HIDING_VAULT_STORAGE_POSITION;
assembly {
s.slot := position
}
}
}
interface NFTLike {
function ownerOf(uint256 _tokenID) view external returns (address);
function implementations(bytes4 _sig) view external returns (address);
}
// SPDX-License-Identifier: BSD-3-Clause
//
// Copyright 2020 Compound Labs, Inc.
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// This contract is copied from https://github.com/compound-finance/compound-protocol
pragma solidity 0.8.6;
contract CTokenStorage {
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Contract which oversees inter-cToken operations
*/
address public comptroller;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
}
abstract contract CToken is CTokenStorage {
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external virtual returns (bool);
function transferFrom(address src, address dst, uint amount) external virtual returns (bool);
function approve(address spender, uint amount) external virtual returns (bool);
function allowance(address owner, address spender) external virtual view returns (uint);
function balanceOf(address owner) external virtual view returns (uint);
function balanceOfUnderlying(address owner) external virtual returns (uint);
function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external virtual view returns (uint);
function supplyRatePerBlock() external virtual view returns (uint);
function totalBorrowsCurrent() external virtual returns (uint);
function borrowBalanceCurrent(address account) external virtual returns (uint);
function borrowBalanceStored(address account) external virtual view returns (uint);
function exchangeRateCurrent() external virtual returns (uint);
function exchangeRateStored() external virtual view returns (uint);
function getCash() external virtual view returns (uint);
function accrueInterest() external virtual returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external virtual returns (uint);
}
abstract contract CErc20 is CToken {
function underlying() external virtual view returns (address);
function mint(uint mintAmount) external virtual returns (uint);
function repayBorrow(uint repayAmount) external virtual returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external virtual returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CToken cTokenCollateral) external virtual returns (uint);
function redeem(uint redeemTokens) external virtual returns (uint);
function redeemUnderlying(uint redeemAmount) external virtual returns (uint);
function borrow(uint borrowAmount) external virtual returns (uint);
}
abstract contract CEther is CToken {
function mint() external virtual payable;
function repayBorrow() external virtual payable;
function repayBorrowBehalf(address borrower) external virtual payable;
function liquidateBorrow(address borrower, CToken cTokenCollateral) external virtual payable;
function redeem(uint redeemTokens) external virtual returns (uint);
function redeemUnderlying(uint redeemAmount) external virtual returns (uint);
function borrow(uint borrowAmount) external virtual returns (uint);
}
abstract contract PriceOracle {
/**
* @notice Get the underlying price of a cToken asset
* @param cToken The cToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(CToken cToken) external virtual view returns (uint);
}
abstract contract Comptroller {
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/// @notice A list of all markets
CToken[] public allMarkets;
/**
* @notice Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
struct Market {
// Whether or not this market is listed
bool isListed;
// Multiplier representing the most one can borrow against their collateral in this market.
// For instance, 0.9 to allow borrowing 90% of collateral value.
// Must be between 0 and 1, and stored as a mantissa.
uint collateralFactorMantissa;
// Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
// Whether or not this market receives COMP
bool isComped;
}
/**
* @notice Official mapping of cTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external virtual returns (uint[] memory);
function exitMarket(address cToken) external virtual returns (uint);
function checkMembership(address account, CToken cToken) external virtual view returns (bool);
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external virtual view returns (uint, uint);
function getAssetsIn(address account) external virtual view returns (address[] memory);
function getHypotheticalAccountLiquidity(
address account,
address cTokenModify,
uint redeemTokens,
uint borrowAmount) external virtual view returns (uint, uint, uint);
function _setPriceOracle(PriceOracle newOracle) external virtual returns (uint);
}
contract SimplePriceOracle is PriceOracle {
mapping(address => uint) prices;
uint256 ethPrice;
event PricePosted(address asset, uint previousPriceMantissa, uint requestedPriceMantissa, uint newPriceMantissa);
function getUnderlyingPrice(CToken cToken) public override view returns (uint) {
if (compareStrings(cToken.symbol(), "cETH")) {
return ethPrice;
} else {
return prices[address(CErc20(address(cToken)).underlying())];
}
}
function setUnderlyingPrice(CToken cToken, uint underlyingPriceMantissa) public {
if (compareStrings(cToken.symbol(), "cETH")) {
ethPrice = underlyingPriceMantissa;
} else {
address asset = address(CErc20(address(cToken)).underlying());
emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa);
prices[asset] = underlyingPriceMantissa;
}
}
function setDirectPrice(address asset, uint price) public {
emit PricePosted(asset, prices[asset], price, price);
prices[asset] = price;
}
// v1 price oracle interface for use as backing of proxy
function assetPrices(address asset) external view returns (uint) {
return prices[asset];
}
function compareStrings(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.8.6;
import "./Compound.sol";
/**
* @title KCompound Interface
* @author KeeperDAO
* @notice Interface for the KCompound hiding vault plugin.
*/
interface IKCompound {
/**
* @notice Calculate the given cToken's balance of this contract.
*
* @param _cToken The address of the cToken contract.
*
* @return Outstanding balance of the given token.
*/
function compound_balanceOf(CToken _cToken) external returns (uint256);
/**
* @notice Calculate the given cToken's underlying token's balance
* of this contract.
*
* @param _cToken The address of the cToken contract.
*
* @return Outstanding balance of the given token.
*/
function compound_balanceOfUnderlying(CToken _cToken) external returns (uint256);
/**
* @notice Calculate the unhealth of this account.
* @dev unhealth of an account starts from 0, if a position
* has an unhealth of more than 100 then the position
* is liquidatable.
*
* @return Unhealth of this account.
*/
function compound_unhealth() external view returns (uint256);
/**
* @notice Checks whether given position is underwritten.
*/
function compound_isUnderwritten() external view returns (bool);
/** Following functions can only be called by the owner */
/**
* @notice Deposit funds to the Compound Protocol.
*
* @param _cToken The address of the cToken contract.
* @param _amount The value of partial loan.
*/
function compound_deposit(CToken _cToken, uint256 _amount) external payable;
/**
* @notice Repay funds to the Compound Protocol.
*
* @param _cToken The address of the cToken contract.
* @param _amount The value of partial loan.
*/
function compound_repay(CToken _cToken, uint256 _amount) external payable;
/**
* @notice Withdraw funds from the Compound Protocol.
*
* @param _to The address of the receiver.
* @param _cToken The address of the cToken contract.
* @param _amount The amount to be withdrawn.
*/
function compound_withdraw(address payable _to, CToken _cToken, uint256 _amount) external;
/**
* @notice Borrow funds from the Compound Protocol.
*
* @param _to The address of the amount receiver.
* @param _cToken The address of the cToken contract.
* @param _amount The value of partial loan.
*/
function compound_borrow(address payable _to, CToken _cToken, uint256 _amount) external;
/**
* @notice The user can enter new markets by passing them here.
*/
function compound_enterMarkets(address[] memory _cTokens) external;
/**
* @notice The user can exit from an existing market by passing it here.
*/
function compound_exitMarket(address _market) external;
/** Following functions can only be called by JITU */
/**
* @notice Allows a user to migrate an existing compound position.
* @dev The user has to approve all the cTokens (he owns) to this
* contract before calling this function, otherwise this contract will
* be reverted.
* @param _amount The amount that needs to be flash lent (should be
* greater than the value of the compund position).
*/
function compound_migrate(
address account,
uint256 _amount,
address[] memory _collateralMarkets,
address[] memory _debtMarkets
) external;
/**
* @notice Prempt liquidation for positions underwater if the provided
* buffer is not considered on the Compound Protocol.
*
* @param _cTokenRepay The cToken for which the loan is being repaid for.
* @param _repayAmount The amount that should be repaid.
* @param _cTokenCollateral The collateral cToken address.
*/
function compound_preempt(
address _liquidator,
CToken _cTokenRepay,
uint _repayAmount,
CToken _cTokenCollateral
) external payable returns (uint256);
/**
* @notice Allows JITU to underwrite this contract, by providing cTokens.
*
* @param _cToken The address of the cToken.
* @param _tokens The amount of the cToken tokens.
*/
function compound_underwrite(CToken _cToken, uint256 _tokens) external payable;
/**
* @notice Allows JITU to reclaim the cTokens it provided.
*/
function compound_reclaim() external;
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.8.6;
import "./IKCompound.sol";
import "./LibCompound.sol";
/**
* @title Compound plugin for the HidingVault
* @author KeeperDAO
* @dev This is the contract logic for the HidingVault compound plugin.
*
* This contract holds the compound position account details for the users, and allows
* users to manage their compound positions by depositing, withdrawing funds, repaying
* existing loans and borrowing.
*
* This contract allows JITU to underwrite loans that are close to getting liquidated so that
* only friendly keepers can liquidate the position, resulting in lower liquidation fees to
* the user. Once a position is either liquidated or comes back to a safe LTV (Loan-To-Value)
* ratio JITU should claim back the assets provided to underwrite the loan.
*
* To migrate an existing compound position we flash lend cTokens greater than the total
* existing compound position value, borrow all the assets that are currently borrowed by the
* user and repay the user's loans. Once all the loans are repaid transfer over the assets from the
* user, then repay the ETH flash loan borrowed in the beginning. `migrate()` function is used by
* the user to migrate a compound position over. The user has to approve all the cTokens he owns
* to this contract before calling the `migrate()` function.
*/
contract KCompound is IKCompound {
using LibCToken for CToken;
address constant JITU = 0x9e43efD070D8E3F8427862A760a37D6325821288;
/**
* @dev revert if the caller is not JITU
*/
modifier onlyJITU() {
require(msg.sender == JITU, "KCompoundPosition: caller is not the MEV protector");
_;
}
/**
* @dev revert if the caller is not the owner
*/
modifier onlyOwner() {
require(msg.sender == LibCompound.owner(), "KCompoundPosition: caller is not the owner");
_;
}
/**
* @dev revert if the position is underwritten
*/
modifier whenNotUnderwritten() {
require(!compound_isUnderwritten(), "LibCompound: operation not allowed when underwritten");
_;
}
/**
* @dev revert if the position is not underwritten
*/
modifier whenUnderwritten() {
require(compound_isUnderwritten(), "LibCompound: operation not allowed when underwritten");
_;
}
/**
* @inheritdoc IKCompound
*/
function compound_deposit(CToken _cToken, uint256 _amount) external payable override {
require(_cToken.isListed(), "KCompound: unsupported cToken address");
_cToken.pullAndApproveUnderlying(msg.sender, address(_cToken), _amount);
_cToken.mint(_amount);
}
/**
* @inheritdoc IKCompound
*/
function compound_withdraw(address payable _to, CToken _cToken, uint256 _amount) external override onlyOwner whenNotUnderwritten {
require(_cToken.isListed(), "KCompound: unsupported cToken address");
_cToken.redeemUnderlying(_amount);
_cToken.transferUnderlying(_to, _amount);
}
/**
* @inheritdoc IKCompound
*/
function compound_borrow(address payable _to, CToken _cToken, uint256 _amount) external override onlyOwner whenNotUnderwritten {
require(_cToken.isListed(), "KCompound: unsupported cToken address");
_cToken.borrow(_amount);
_cToken.transferUnderlying(_to, _amount);
}
/**
* @inheritdoc IKCompound
*/
function compound_repay(CToken _cToken, uint256 _amount) external payable override {
require(_cToken.isListed(), "KCompound: unsupported cToken address");
_cToken.pullAndApproveUnderlying(msg.sender, address(_cToken), _amount);
_cToken.repayBorrow(_amount);
}
/**
* @inheritdoc IKCompound
*/
function compound_preempt(
address _liquidator,
CToken _cTokenRepay,
uint _repayAmount,
CToken _cTokenCollateral
) external payable override onlyJITU returns (uint256) {
return LibCompound.preempt(_cTokenRepay, _liquidator, _repayAmount, _cTokenCollateral);
}
/**
* @inheritdoc IKCompound
*/
function compound_migrate(
address _account,
uint256 _amount,
address[] memory _collateralMarkets,
address[] memory _debtMarkets
) external override onlyJITU {
LibCompound.migrate(
_account,
_amount,
_collateralMarkets,
_debtMarkets
);
}
/**
* @inheritdoc IKCompound
*/
function compound_underwrite(CToken _cToken, uint256 _tokens) external payable override onlyJITU whenNotUnderwritten {
LibCompound.underwrite(_cToken, _tokens);
}
/**
* @inheritdoc IKCompound
*/
function compound_reclaim() external override onlyJITU whenUnderwritten {
LibCompound.reclaim();
}
/**
* @inheritdoc IKCompound
*/
function compound_enterMarkets(address[] memory _markets) external override onlyOwner {
LibCompound.enterMarkets(_markets);
}
/**
* @inheritdoc IKCompound
*/
function compound_exitMarket(address _market) external override onlyOwner whenNotUnderwritten {
LibCompound.exitMarket(_market);
}
/**
* @inheritdoc IKCompound
*/
function compound_balanceOfUnderlying(CToken _cToken) external override returns (uint256) {
return LibCompound.balanceOfUnderlying(_cToken);
}
/**
* @inheritdoc IKCompound
*/
function compound_balanceOf(CToken _cToken) external view override returns (uint256) {
return LibCompound.balanceOf(_cToken);
}
/**
* @inheritdoc IKCompound
*/
function compound_unhealth() external override view returns (uint256) {
return LibCompound.unhealth();
}
/**
* @inheritdoc IKCompound
*/
function compound_isUnderwritten() public override view returns (bool) {
return LibCompound.isUnderwritten();
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./Compound.sol";
/**
* @title Library to simplify CToken interaction
* @author KeeperDAO
* @dev this library abstracts cERC20 and cEther interactions.
*/
library LibCToken {
using SafeERC20 for IERC20;
// Network: MAINNET
Comptroller constant COMPTROLLER = Comptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
CEther constant CETHER = CEther(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5);
/**
* @notice checks if the given cToken is listed as a valid market on
* comptroller.
*
* @param _cToken cToken address
*/
function isListed(CToken _cToken) internal view returns (bool listed) {
(listed, , ) = COMPTROLLER.markets(address(_cToken));
}
/**
* @notice returns the given cToken's underlying token address.
*
* @param _cToken cToken address
*/
function underlying(CToken _cToken) internal view returns (address) {
if (address(_cToken) == address(CETHER)) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
} else {
return CErc20(address(_cToken)).underlying();
}
}
/**
* @notice redeems given amount of underlying tokens.
*
* @param _cToken cToken address
* @param _amount underlying token amount
*/
function redeemUnderlying(CToken _cToken, uint _amount) internal {
if (address(_cToken) == address(CETHER)) {
require(CETHER.redeemUnderlying(_amount) == 0, "failed to redeem ether");
} else {
require(CErc20(address(_cToken)).redeemUnderlying(_amount) == 0, "failed to redeem ERC20");
}
}
/**
* @notice borrows given amount of underlying tokens.
*
* @param _cToken cToken address
* @param _amount underlying token amount
*/
function borrow(CToken _cToken, uint _amount) internal {
if (address(_cToken) == address(CETHER)) {
require(CETHER.borrow(_amount) == 0, "failed to borrow ether");
} else {
require(CErc20(address(_cToken)).borrow(_amount) == 0, "failed to borrow ERC20");
}
}
/**
* @notice deposits given amount of underlying tokens.
*
* @param _cToken cToken address
* @param _amount underlying token amount
*/
function mint(CToken _cToken, uint _amount) internal {
if (address(_cToken) == address(CETHER)) {
CETHER.mint{ value: _amount }();
} else {
require(CErc20(address(_cToken)).mint(_amount) == 0, "failed to mint cERC20");
}
}
/**
* @notice repay given amount of underlying tokens.
*
* @param _cToken cToken address
* @param _amount underlying token amount
*/
function repayBorrow(CToken _cToken, uint _amount) internal {
if (address(_cToken) == address(CETHER)) {
CETHER.repayBorrow{ value: _amount }();
} else {
require(CErc20(address(_cToken)).repayBorrow(_amount) == 0, "failed to mint cERC20");
}
}
/**
* @notice repay given amount of underlying tokens on behalf of the borrower.
*
* @param _cToken cToken address
* @param _borrower borrower address
* @param _amount underlying token amount
*/
function repayBorrowBehalf(CToken _cToken, address _borrower, uint _amount) internal {
if (address(_cToken) == address(CETHER)) {
CETHER.repayBorrowBehalf{ value: _amount }(_borrower);
} else {
require(CErc20(address(_cToken)).repayBorrowBehalf(_borrower, _amount) == 0, "failed to mint cERC20");
}
}
/**
* @notice transfer given amount of underlying tokens to the given address.
*
* @param _cToken cToken address
* @param _to reciever address
* @param _amount underlying token amount
*/
function transferUnderlying(CToken _cToken, address payable _to, uint256 _amount) internal {
if (address(_cToken) == address(CETHER)) {
(bool success,) = _to.call{ value: _amount }("");
require(success, "Transfer Failed");
} else {
IERC20(CErc20(address(_cToken)).underlying()).safeTransfer(_to, _amount);
}
}
/**
* @notice approve given amount of underlying tokens to the given address.
*
* @param _cToken cToken address
* @param _spender spender address
* @param _amount underlying token amount
*/
function approveUnderlying(CToken _cToken, address _spender, uint256 _amount) internal {
if (address(_cToken) != address(CETHER)) {
IERC20 token = IERC20(CErc20(address(_cToken)).underlying());
token.safeIncreaseAllowance(_spender, _amount);
}
}
/**
* @notice pull approve given amount of underlying tokens to the given address.
*
* @param _cToken cToken address
* @param _from address from which the funds need to be pulled
* @param _to address to which the funds are approved to
* @param _amount underlying token amount
*/
function pullAndApproveUnderlying(CToken _cToken, address _from, address _to, uint256 _amount) internal {
if (address(_cToken) == address(CETHER)) {
require(msg.value == _amount, "failed to mint CETHER");
} else {
IERC20 token = IERC20(CErc20(address(_cToken)).underlying());
token.safeTransferFrom(_from, address(this), _amount);
token.safeIncreaseAllowance(_to, _amount);
}
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.8.6;
import "./LibCToken.sol";
import "../../LibHidingVault.sol";
/**
* @title Buffer accounting library for KCompound
* @author KeeperDAO
* @dev This library handles existing compound position migration.
* @dev This library implements all the logic for the individual kCompound
* position contracts.
*/
library LibCompound {
using LibCToken for CToken;
// KCOMPOUND_STORAGE_POSITION = keccak256("keeperdao.hiding-vault.compound.storage")
bytes32 constant KCOMPOUND_STORAGE_POSITION = 0x4f39ec42b5bbf77786567b02cbf043f85f0f917cbaa97d8df56931d77a999205;
/**
* State for LibCompound
*/
struct State {
uint256 bufferAmount;
CToken bufferToken;
}
/**
* @notice Load the LibCompound State for the given user
*/
function state() internal pure returns (State storage s) {
bytes32 position = KCOMPOUND_STORAGE_POSITION;
assembly {
s.slot := position
}
}
/**
* @dev this function will be called by the KeeperDAO's LiquidityPool.
* @param _account The address of the compund position owner.
* @param _tokens The amount that is being flash lent.
*/
function migrate(
address _account,
uint256 _tokens,
address[] memory _collateralMarkets,
address[] memory _debtMarkets
) internal {
// Enter markets
enterMarkets(_collateralMarkets);
// Migrate all the cToken Loans.
if (_debtMarkets.length != 0) migrateLoans(_debtMarkets, _account);
// Migrate all the assets from compound.
if (_collateralMarkets.length != 0) migrateFunds(_collateralMarkets, _account);
// repay CETHER
require(
CToken(_collateralMarkets[0]).transfer(msg.sender, _tokens),
"LibCompound: failed to return funds during migration"
);
}
/**
* @notice this function borrows required amount of ETH/ERC20 tokens,
* repays the ETH/ERC20 loan (if it exists) on behalf of the
* compound position owner.
*/
function migrateLoans(address[] memory _cTokens, address _account) private {
for (uint32 i = 0; i < _cTokens.length; i++) {
CToken cToken = CToken(_cTokens[i]);
uint256 borrowBalance = cToken.borrowBalanceCurrent(_account);
cToken.borrow(borrowBalance);
cToken.approveUnderlying(address(cToken), borrowBalance);
cToken.repayBorrowBehalf(_account, borrowBalance);
}
}
/**
* @notice transfer all the assets from the account.
*/
function migrateFunds(address[] memory _cTokens, address _account) private {
for (uint32 i = 0; i < _cTokens.length; i++) {
CToken cToken = CToken(_cTokens[i]);
require(cToken.transferFrom(
_account,
address(this),
cToken.balanceOf(_account)
), "LibCompound: failed to transfer CETHER");
}
}
/**
* @notice Prempt liquidation for positions underwater if the provided
* buffer is not considered on the Compound Protocol.
*
* @param _liquidator The address of the liquidator.
* @param _cTokenRepaid The repay cToken address.
* @param _repayAmount The amount that should be repaid.
* @param _cTokenCollateral The collateral cToken address.
*/
function preempt(
CToken _cTokenRepaid,
address _liquidator,
uint _repayAmount,
CToken _cTokenCollateral
) internal returns (uint256) {
// Check whether the user's position is liquidatable, and if it is
// return the amount of tokens that can be seized for the given loan,
// token pair.
uint seizeTokens = seizeTokenAmount(
address(_cTokenRepaid),
address(_cTokenCollateral),
_repayAmount
);
// This is a preemptive liquidation, so it would just repay the given loan
// and seize the corresponding amount of tokens.
_cTokenRepaid.pullAndApproveUnderlying(_liquidator, address(_cTokenRepaid), _repayAmount);
_cTokenRepaid.repayBorrow(_repayAmount);
require(_cTokenCollateral.transfer(_liquidator, seizeTokens), "LibCompound: failed to transfer cTokens");
return seizeTokens;
}
/**
* @notice Allows JITU to underwrite this contract, by providing cTokens.
*
* @param _cToken The address of the token.
* @param _tokens The tokens being transferred.
*/
function underwrite(CToken _cToken, uint256 _tokens) internal {
require(_tokens * 3 <= _cToken.balanceOf(address(this)),
"LibCompound: underwrite pre-conditions not met");
State storage s = state();
s.bufferToken = _cToken;
s.bufferAmount = _tokens;
blacklistCTokens();
}
/**
* @notice Allows JITU to reclaim the cTokens it provided.
*/
function reclaim() internal {
State storage s = state();
require(s.bufferToken.transfer(msg.sender, s.bufferAmount), "LibCompound: failed to return cTokens");
s.bufferToken = CToken(address(0));
s.bufferAmount = 0;
whitelistCTokens();
}
/**
* @notice Blacklist all the collateral assets.
*/
function blacklistCTokens() internal {
address[] memory cTokens = LibCToken.COMPTROLLER.getAssetsIn(address(this));
for (uint32 i = 0; i < cTokens.length; i++) {
LibHidingVault.state().recoverableTokensBlacklist[cTokens[i]] = true;
}
}
/**
* @notice Whitelist all the collateral assets.
*/
function whitelistCTokens() internal {
address[] memory cTokens = LibCToken.COMPTROLLER.getAssetsIn(address(this));
for (uint32 i = 0; i < cTokens.length; i++) {
LibHidingVault.state().recoverableTokensBlacklist[cTokens[i]] = false;
}
}
/**
* @notice check whether the position is liquidatable,
* if it is calculate the amount of tokens
* that can be seized.
*
* @param cTokenRepaid the token that is being repaid.
* @param cTokenSeized the token that is being seized.
* @param repayAmount the amount being repaid.
*
* @return the amount of tokens that need to be seized.
*/
function seizeTokenAmount(
address cTokenRepaid,
address cTokenSeized,
uint repayAmount
) internal returns (uint) {
State storage s = state();
// accrue interest
require(CToken(cTokenRepaid).accrueInterest() == 0, "LibCompound: failed to accrue interest on cTokenRepaid");
require(CToken(cTokenSeized).accrueInterest() == 0, "LibCompound: failed to accrue interest on cTokenSeized");
// The borrower must have shortfall in order to be liquidatable
(uint err, , uint shortfall) = LibCToken.COMPTROLLER.getHypotheticalAccountLiquidity(address(this), address(s.bufferToken), s.bufferAmount, 0);
require(err == 0, "LibCompound: failed to get account liquidity");
require(shortfall != 0, "LibCompound: insufficient shortfall to liquidate");
// The liquidator may not repay more than what is allowed by the closeFactor
uint borrowBalance = CToken(cTokenRepaid).borrowBalanceStored(address(this));
uint maxClose = mulScalarTruncate(LibCToken.COMPTROLLER.closeFactorMantissa(), borrowBalance);
require(repayAmount <= maxClose, "LibCompound: repay amount cannot exceed the max close amount");
// Calculate the amount of tokens that can be seized
(uint errCode2, uint seizeTokens) = LibCToken.COMPTROLLER
.liquidateCalculateSeizeTokens(cTokenRepaid, cTokenSeized, repayAmount);
require(errCode2 == 0, "LibCompound: failed to calculate seize token amount");
// Check that the amount of tokens being seized is less than the user's
// cToken balance
uint256 seizeTokenCollateral = CToken(cTokenSeized).balanceOf(address(this));
if (cTokenSeized == address(s.bufferToken)) {
seizeTokenCollateral = seizeTokenCollateral - s.bufferAmount;
}
require(seizeTokenCollateral >= seizeTokens, "LibCompound: insufficient liquidity");
return seizeTokens;
}
/**
* @notice calculates the collateral value of the given cToken amount.
* @dev collateral value means the amount of loan that can be taken without
* falling below the collateral requirement.
*
* @param _cToken the compound token we are calculating the collateral for.
* @param _tokens number of compound tokens.
*
* @return max borrow value for the given compound tokens in USD.
*/
function collateralValueInUSD(CToken _cToken, uint256 _tokens) internal view returns (uint256) {
// read the exchange rate from the cToken
uint256 exchangeRate = _cToken.exchangeRateStored();
// read the collateralFactor from the LibCToken.COMPTROLLER
(, uint256 collateralFactor, ) = LibCToken.COMPTROLLER.markets(address(_cToken));
// read the underlying token prive from the Compound's oracle
uint256 oraclePrice = LibCToken.COMPTROLLER.oracle().getUnderlyingPrice(_cToken);
require(oraclePrice != 0, "LibCompound: failed to get underlying price from the oracle");
return mulExp3AndScalarTruncate(collateralFactor, exchangeRate, oraclePrice, _tokens);
}
/**
* @notice Calculate the given cToken's underlying token balance of the caller.
*
* @param _cToken The address of the cToken contract.
*
* @return Outstanding balance in the given token.
*/
function balanceOfUnderlying(CToken _cToken) internal returns (uint256) {
return mulScalarTruncate(_cToken.exchangeRateCurrent(), balanceOf(_cToken));
}
/**
* @notice Calculate the given cToken's balance of the caller.
*
* @param _cToken The address of the cToken contract.
*
* @return Outstanding balance of the given token.
*/
function balanceOf(CToken _cToken) internal view returns (uint256) {
State storage s = state();
uint256 cTokenBalance = _cToken.balanceOf(address(this));
if (s.bufferToken == _cToken) {
cTokenBalance -= s.bufferAmount;
}
return cTokenBalance;
}
/**
* @notice new markets can be entered by calling this function.
*/
function enterMarkets(address[] memory _cTokens) internal {
uint[] memory retVals = LibCToken.COMPTROLLER.enterMarkets(_cTokens);
for (uint i; i < retVals.length; i++) {
require(retVals[i] == 0, "LibCompound: failed to enter market");
}
}
/**
* @notice existing markets can be exited by calling this function
*/
function exitMarket(address _cToken) internal {
require(
LibCToken.COMPTROLLER.exitMarket(_cToken) == 0,
"LibCompound: failed to exit a market"
);
}
/**
* @notice unhealth of the given account, the position is underwater
* if this value is greater than 100
* @dev if the account is empty, this fn returns an unhealth of 0
*
* @return unhealth of the account
*/
function unhealth() internal view returns (uint256) {
uint256 totalCollateralValue;
State storage s = state();
address[] memory cTokens = LibCToken.COMPTROLLER.getAssetsIn(address(this));
// calculate the total collateral value of this account
for (uint i = 0; i < cTokens.length; i++) {
totalCollateralValue = totalCollateralValue + collateralValue(CToken(cTokens[i]));
}
if (totalCollateralValue > 0) {
uint256 totalBorrowValue;
// get the account liquidity
(uint err, uint256 liquidity, uint256 shortFall) =
LibCToken.COMPTROLLER.getHypotheticalAccountLiquidity(
address(this),
address(s.bufferToken),
s.bufferAmount,
0
);
require(err == 0, "LibCompound: failed to calculate account liquidity");
if (liquidity == 0) {
totalBorrowValue = totalCollateralValue + shortFall;
} else {
totalBorrowValue = totalCollateralValue - liquidity;
}
return (totalBorrowValue * 100) / totalCollateralValue;
}
return 0;
}
/**
* @notice calculate the collateral value of the given cToken
*
* @return collateral value of the given cToken
*/
function collateralValue(CToken cToken) internal view returns (uint256) {
State storage s = state();
uint256 bufferAmount;
if (s.bufferToken == cToken) {
bufferAmount = s.bufferAmount;
}
return collateralValueInUSD(
cToken,
cToken.balanceOf(address(this)) - bufferAmount
);
}
/**
* @notice checks whether the given position is underwritten or not
*
* @return underwritten status of the caller
*/
function isUnderwritten() internal view returns (bool) {
State storage s = state();
return (s.bufferAmount != 0 && s.bufferToken != CToken(address(0)));
}
/**
* @notice checks the owner of this vault
*
* @return address of the owner
*/
function owner() internal view returns (address) {
return LibHidingVault.state().nft.ownerOf(uint256(uint160(address(this))));
}
/** Exponential Math */
function mulExp3AndScalarTruncate(uint256 a, uint256 b, uint256 c, uint256 d) internal pure returns (uint256) {
return mulScalarTruncate(mulExp(mulExp(a, b), c), d);
}
function mulExp(uint256 _a, uint256 _b) internal pure returns (uint256) {
return (_a * _b + 5e17) / 1e18;
}
function mulScalarTruncate(uint256 _a, uint256 _b) internal pure returns (uint256) {
return (_a * _b) / 1e18;
}
}
interface Weth {
function balanceOf(address owner) external view returns (uint);
function deposit() external payable;
function withdraw(uint256 _amount) external;
function approve(address spender, uint256 amount) external returns (bool);
function transfer(address spender, uint256 amount) external returns (bool);
}
interface NFT {
function jitu() external view returns (address);
function ownerOf(uint256 _tokenID) external view returns (address);
}
| * @notice checks if the given cToken is listed as a valid market on comptroller. @param _cToken cToken address/ | function isListed(CToken _cToken) internal view returns (bool listed) {
(listed, , ) = COMPTROLLER.markets(address(_cToken));
}
| 118,184 | [
1,
12366,
309,
326,
864,
276,
1345,
353,
12889,
487,
279,
923,
13667,
603,
532,
337,
1539,
18,
225,
389,
71,
1345,
276,
1345,
1758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
28106,
329,
12,
1268,
969,
389,
71,
1345,
13,
2713,
1476,
1135,
261,
6430,
12889,
13,
288,
203,
3639,
261,
18647,
16,
269,
262,
273,
5423,
1856,
25353,
18,
3355,
2413,
12,
2867,
24899,
71,
1345,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x3b985118468164b310C5254b0710888dd57c7599/sources/contracts/pool/PoolRewards.sol | @notice Override of transfer function with rewards corrections @param from Account to transfer from @param to Account to transfer to @param amount Amount to transfer | function _transfer(
address from,
address to,
uint256 amount
) internal virtual override {
_accrueInterest();
_distributeReward();
super._transfer(from, to, amount);
_magnifiedRewardCorrections[from] += (_magnifiedRewardPerShare * amount)
.toInt256();
_magnifiedRewardCorrections[to] -= (_magnifiedRewardPerShare * amount)
.toInt256();
}
| 3,086,515 | [
1,
6618,
434,
7412,
445,
598,
283,
6397,
15104,
87,
225,
628,
6590,
358,
7412,
628,
225,
358,
6590,
358,
7412,
358,
225,
3844,
16811,
358,
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
]
| [
1,
1,
1,
1,
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
]
| [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
5024,
3849,
288,
203,
3639,
389,
8981,
86,
344,
29281,
5621,
203,
3639,
389,
2251,
887,
17631,
1060,
5621,
203,
203,
3639,
2240,
6315,
13866,
12,
2080,
16,
358,
16,
3844,
1769,
203,
3639,
389,
4527,
82,
939,
17631,
1060,
20884,
87,
63,
2080,
65,
1011,
261,
67,
4527,
82,
939,
17631,
1060,
2173,
9535,
380,
3844,
13,
203,
5411,
263,
869,
1702,
5034,
5621,
203,
3639,
389,
4527,
82,
939,
17631,
1060,
20884,
87,
63,
869,
65,
3947,
261,
67,
4527,
82,
939,
17631,
1060,
2173,
9535,
380,
3844,
13,
203,
5411,
263,
869,
1702,
5034,
5621,
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
]
|
./full_match/1/0xE10baE1903e48B4F544d319759e7f71Df9cf9A59/sources/contracts/Pool.sol | * @dev Internal function to get the past votes of an account at a specific block. @param account The account's address. @param blockNumber The block number. @return The past votes of the account at the given block./ | function _getPastVotes(
address account,
uint256 blockNumber
) internal view override returns (uint256) {
return getGovernanceToken().getPastVotes(account, blockNumber);
}
| 17,152,448 | [
1,
3061,
445,
358,
336,
326,
8854,
19588,
434,
392,
2236,
622,
279,
2923,
1203,
18,
225,
2236,
1021,
2236,
1807,
1758,
18,
225,
1203,
1854,
1021,
1203,
1300,
18,
327,
1021,
8854,
19588,
434,
326,
2236,
622,
326,
864,
1203,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
588,
52,
689,
29637,
12,
203,
3639,
1758,
2236,
16,
203,
3639,
2254,
5034,
1203,
1854,
203,
565,
262,
2713,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
7162,
1643,
82,
1359,
1345,
7675,
588,
52,
689,
29637,
12,
4631,
16,
1203,
1854,
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
]
|
//Address: 0xd2f81cd7a20d60c0d558496c7169a20968389b40
//Contract name: EtherbotsCore
//Balance: 0 Ether
//Verification Date: 3/4/2018
//Transacion Count: 52578
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// Pause functionality taken from OpenZeppelin. License below.
/* The MIT License (MIT)
Copyright (c) 2016 Smart Contract Solutions, Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: */
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event SetPaused(bool paused);
// starts unpaused
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);
_;
}
function pause() public onlyOwner whenNotPaused returns (bool) {
paused = true;
SetPaused(paused);
return true;
}
function unpause() public onlyOwner whenPaused returns (bool) {
paused = false;
SetPaused(paused);
return true;
}
}
contract EtherbotsPrivileges is Pausable {
event ContractUpgrade(address newContract);
}
// This contract implements both the original ERC-721 standard and
// the proposed 'deed' standard of 841
// I don't know which standard will eventually be adopted - support both for now
/// @title Interface for contracts conforming to ERC-721: Deed Standard
/// @author William Entriken (https://phor.net), et. al.
/// @dev Specification at https://github.com/ethereum/eips/841
/// can read the comments there
contract ERC721 {
// COMPLIANCE WITH ERC-165 (DRAFT)
/// @dev ERC-165 (draft) interface signature for itself
bytes4 internal constant INTERFACE_SIGNATURE_ERC165 =
bytes4(keccak256("supportsInterface(bytes4)"));
/// @dev ERC-165 (draft) interface signature for ERC721
bytes4 internal constant INTERFACE_SIGNATURE_ERC721 =
bytes4(keccak256("ownerOf(uint256)")) ^
bytes4(keccak256("countOfDeeds()")) ^
bytes4(keccak256("countOfDeedsByOwner(address)")) ^
bytes4(keccak256("deedOfOwnerByIndex(address,uint256)")) ^
bytes4(keccak256("approve(address,uint256)")) ^
bytes4(keccak256("takeOwnership(uint256)"));
function supportsInterface(bytes4 _interfaceID) external pure returns (bool);
// PUBLIC QUERY FUNCTIONS //////////////////////////////////////////////////
function ownerOf(uint256 _deedId) public view returns (address _owner);
function countOfDeeds() external view returns (uint256 _count);
function countOfDeedsByOwner(address _owner) external view returns (uint256 _count);
function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _deedId);
// TRANSFER MECHANISM //////////////////////////////////////////////////////
event Transfer(address indexed from, address indexed to, uint256 indexed deedId);
event Approval(address indexed owner, address indexed approved, uint256 indexed deedId);
function approve(address _to, uint256 _deedId) external payable;
function takeOwnership(uint256 _deedId) external payable;
}
/// @title Metadata extension to ERC-721 interface
/// @author William Entriken (https://phor.net)
/// @dev Specification at https://github.com/ethereum/eips/issues/XXXX
contract ERC721Metadata is ERC721 {
bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata =
bytes4(keccak256("name()")) ^
bytes4(keccak256("symbol()")) ^
bytes4(keccak256("deedUri(uint256)"));
function name() public pure returns (string n);
function symbol() public pure returns (string s);
/// @notice A distinct URI (RFC 3986) for a given token.
/// @dev If:
/// * The URI is a URL
/// * The URL is accessible
/// * The URL points to a valid JSON file format (ECMA-404 2nd ed.)
/// * The JSON base element is an object
/// then these names of the base element SHALL have special meaning:
/// * "name": A string identifying the item to which `_deedId` grants
/// ownership
/// * "description": A string detailing the item to which `_deedId` grants
/// ownership
/// * "image": A URI pointing to a file of image/* mime type representing
/// the item to which `_deedId` grants ownership
/// Wallets and exchanges MAY display this to the end user.
/// Consider making any images at a width between 320 and 1080 pixels and
/// aspect ratio between 1.91:1 and 4:5 inclusive.
function deedUri(uint256 _deedId) external view returns (string _uri);
}
/// @title Enumeration extension to ERC-721 interface
/// @author William Entriken (https://phor.net)
/// @dev Specification at https://github.com/ethereum/eips/issues/XXXX
contract ERC721Enumerable is ERC721Metadata {
/// @dev ERC-165 (draft) interface signature for ERC721
bytes4 internal constant INTERFACE_SIGNATURE_ERC721Enumerable =
bytes4(keccak256("deedByIndex()")) ^
bytes4(keccak256("countOfOwners()")) ^
bytes4(keccak256("ownerByIndex(uint256)"));
function deedByIndex(uint256 _index) external view returns (uint256 _deedId);
function countOfOwners() external view returns (uint256 _count);
function ownerByIndex(uint256 _index) external view returns (address _owner);
}
contract ERC721Original {
bytes4 constant INTERFACE_SIGNATURE_ERC721Original =
bytes4(keccak256("totalSupply()")) ^
bytes4(keccak256("balanceOf(address)")) ^
bytes4(keccak256("ownerOf(uint256)")) ^
bytes4(keccak256("approve(address,uint256)")) ^
bytes4(keccak256("takeOwnership(uint256)")) ^
bytes4(keccak256("transfer(address,uint256)"));
// Core functions
function implementsERC721() public pure returns (bool);
function totalSupply() public view returns (uint256 _totalSupply);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint _tokenId) public view returns (address _owner);
function approve(address _to, uint _tokenId) external payable;
function transferFrom(address _from, address _to, uint _tokenId) public;
function transfer(address _to, uint _tokenId) public payable;
// Optional functions
function name() public pure returns (string _name);
function symbol() public pure returns (string _symbol);
function tokenOfOwnerByIndex(address _owner, uint _index) external view returns (uint _tokenId);
function tokenMetadata(uint _tokenId) public view returns (string _infoUrl);
// Events
// event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
// event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
}
contract ERC721AllImplementations is ERC721Original, ERC721Enumerable {
}
contract EtherbotsBase is EtherbotsPrivileges {
function EtherbotsBase() public {
// scrapyard = address(this);
}
/*** EVENTS ***/
/// Forge fires when a new part is created - 4 times when a crate is opened,
/// and once when a battle takes place. Also has fires when
/// parts are combined in the furnace.
event Forge(address owner, uint256 partID, Part part);
/// Transfer event as defined in ERC721.
event Transfer(address from, address to, uint256 tokenId);
/*** DATA TYPES ***/
/// The main struct representation of a robot part. Each robot in Etherbots is represented by four copies
/// of this structure, one for each of the four parts comprising it:
/// 1. Right Arm (Melee),
/// 2. Left Arm (Defence),
/// 3. Head (Turret),
/// 4. Body.
// store token id on this?
struct Part {
uint32 tokenId;
uint8 partType;
uint8 partSubType;
uint8 rarity;
uint8 element;
uint32 battlesLastDay;
uint32 experience;
uint32 forgeTime;
uint32 battlesLastReset;
}
// Part type - can be shared with other part factories.
uint8 constant DEFENCE = 1;
uint8 constant MELEE = 2;
uint8 constant BODY = 3;
uint8 constant TURRET = 4;
// Rarity - can be shared with other part factories.
uint8 constant STANDARD = 1;
uint8 constant SHADOW = 2;
uint8 constant GOLD = 3;
// Store a user struct
// in order to keep track of experience and perk choices.
// This perk tree is a binary tree, efficiently encodable as an array.
// 0 reflects no perk selected. 1 is first choice. 2 is second. 3 is both.
// Each choice costs experience (deducted from user struct).
/*** ~~~~~ROBOT PERKS~~~~~ ***/
// PERK 1: ATTACK vs DEFENCE PERK CHOICE.
// Choose
// PERK TWO ATTACK/ SHOOT, or DEFEND/DODGE
// PERK 2: MECH vs ELEMENTAL PERK CHOICE ---
// Choose steel and electric (Mech path), or water and fire (Elemetal path)
// (... will the mechs win the war for Ethertopia? or will the androids
// be deluged in flood and fire? ...)
// PERK 3: Commit to a specific elemental pathway:
// 1. the path of steel: the iron sword; the burning frying pan!
// 2. the path of electricity: the deadly taser, the fearsome forcefield
// 3. the path of water: high pressure water blasters have never been so cool
// 4. the path of fire!: we will hunt you down, Aang...
struct User {
// address userAddress;
uint32 numShards; //limit shards to upper bound eg 10000
uint32 experience;
uint8[32] perks;
}
//Maintain an array of all users.
// User[] public users;
// Store a map of the address to a uint representing index of User within users
// we check if a user exists at multiple points, every time they acquire
// via a crate or the market. Users can also manually register their address.
mapping ( address => User ) public addressToUser;
// Array containing the structs of all parts in existence. The ID
// of each part is an index into this array.
Part[] parts;
// Mapping from part IDs to to owning address. Should always exist.
mapping (uint256 => address) public partIndexToOwner;
// A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count. REMOVE?
mapping (address => uint256) addressToTokensOwned;
// Mapping from Part ID to an address approved to call transferFrom().
// maximum of one approved address for transfer at any time.
mapping (uint256 => address) public partIndexToApproved;
address auction;
// address scrapyard;
// Array to store approved battle contracts.
// Can only ever be added to, not removed from.
// Once a ruleset is published, you will ALWAYS be able to use that contract
address[] approvedBattles;
function getUserByAddress(address _user) public view returns (uint32, uint8[32]) {
return (addressToUser[_user].experience, addressToUser[_user].perks);
}
// Transfer a part to an address
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// No cap on number of parts
// Very unlikely to ever be 2^256 parts owned by one account
// Shouldn't waste gas checking for overflow
// no point making it less than a uint --> mappings don't pack
addressToTokensOwned[_to]++;
// transfer ownership
partIndexToOwner[_tokenId] = _to;
// New parts are transferred _from 0x0, but we can't account that address.
if (_from != address(0)) {
addressToTokensOwned[_from]--;
// clear any previously approved ownership exchange
delete partIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
function getPartById(uint _id) external view returns (
uint32 tokenId,
uint8 partType,
uint8 partSubType,
uint8 rarity,
uint8 element,
uint32 battlesLastDay,
uint32 experience,
uint32 forgeTime,
uint32 battlesLastReset
) {
Part memory p = parts[_id];
return (p.tokenId, p.partType, p.partSubType, p.rarity, p.element, p.battlesLastDay, p.experience, p.forgeTime, p.battlesLastReset);
}
function substring(string str, uint startIndex, uint endIndex) internal pure returns (string) {
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(endIndex-startIndex);
for (uint i = startIndex; i < endIndex; i++) {
result[i-startIndex] = strBytes[i];
}
return string(result);
}
// helper functions adapted from Jossie Calderon on stackexchange
function stringToUint32(string s) internal pure returns (uint32) {
bytes memory b = bytes(s);
uint result = 0;
for (uint i = 0; i < b.length; i++) { // c = b[i] was not needed
if (b[i] >= 48 && b[i] <= 57) {
result = result * 10 + (uint(b[i]) - 48); // bytes and int are not compatible with the operator -.
}
}
return uint32(result);
}
function stringToUint8(string s) internal pure returns (uint8) {
return uint8(stringToUint32(s));
}
function uintToString(uint v) internal pure returns (string) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory s = new bytes(i); // i + 1 is inefficient
for (uint j = 0; j < i; j++) {
s[j] = reversed[i - j - 1]; // to avoid the off-by-one error
}
string memory str = string(s);
return str;
}
}
contract EtherbotsNFT is EtherbotsBase, ERC721Enumerable, ERC721Original {
function supportsInterface(bytes4 _interfaceID) external pure returns (bool) {
return (_interfaceID == ERC721Original.INTERFACE_SIGNATURE_ERC721Original) ||
(_interfaceID == ERC721.INTERFACE_SIGNATURE_ERC721) ||
(_interfaceID == ERC721Metadata.INTERFACE_SIGNATURE_ERC721Metadata) ||
(_interfaceID == ERC721Enumerable.INTERFACE_SIGNATURE_ERC721Enumerable);
}
function implementsERC721() public pure returns (bool) {
return true;
}
function name() public pure returns (string _name) {
return "Etherbots";
}
function symbol() public pure returns (string _smbol) {
return "ETHBOT";
}
// total supply of parts --> as no parts are ever deleted, this is simply
// the total supply of parts ever created
function totalSupply() public view returns (uint) {
return parts.length;
}
/// @notice Returns the total number of deeds currently in existence.
/// @dev Required for ERC-721 compliance.
function countOfDeeds() external view returns (uint256) {
return parts.length;
}
//--/ internal function which checks whether the token with id (_tokenId)
/// is owned by the (_claimant) address
function owns(address _owner, uint256 _tokenId) public view returns (bool) {
return (partIndexToOwner[_tokenId] == _owner);
}
/// internal function which checks whether the token with id (_tokenId)
/// is owned by the (_claimant) address
function ownsAll(address _owner, uint256[] _tokenIds) public view returns (bool) {
require(_tokenIds.length > 0);
for (uint i = 0; i < _tokenIds.length; i++) {
if (partIndexToOwner[_tokenIds[i]] != _owner) {
return false;
}
}
return true;
}
function _approve(uint256 _tokenId, address _approved) internal {
partIndexToApproved[_tokenId] = _approved;
}
function _approvedFor(address _newOwner, uint256 _tokenId) internal view returns (bool) {
return (partIndexToApproved[_tokenId] == _newOwner);
}
function ownerByIndex(uint256 _index) external view returns (address _owner){
return partIndexToOwner[_index];
}
// returns the NUMBER of tokens owned by (_owner)
function balanceOf(address _owner) public view returns (uint256 count) {
return addressToTokensOwned[_owner];
}
function countOfDeedsByOwner(address _owner) external view returns (uint256) {
return balanceOf(_owner);
}
// transfers a part to another account
function transfer(address _to, uint256 _tokenId) public whenNotPaused payable {
// payable for ERC721 --> don't actually send eth @_@
require(msg.value == 0);
// Safety checks to prevent accidental transfers to common accounts
require(_to != address(0));
require(_to != address(this));
// can't transfer parts to the auction contract directly
require(_to != address(auction));
// can't transfer parts to any of the battle contracts directly
for (uint j = 0; j < approvedBattles.length; j++) {
require(_to != approvedBattles[j]);
}
// Cannot send tokens you don't own
require(owns(msg.sender, _tokenId));
// perform state changes necessary for transfer
_transfer(msg.sender, _to, _tokenId);
}
// transfers a part to another account
function transferAll(address _to, uint256[] _tokenIds) public whenNotPaused payable {
require(msg.value == 0);
// Safety checks to prevent accidental transfers to common accounts
require(_to != address(0));
require(_to != address(this));
// can't transfer parts to the auction contract directly
require(_to != address(auction));
// can't transfer parts to any of the battle contracts directly
for (uint j = 0; j < approvedBattles.length; j++) {
require(_to != approvedBattles[j]);
}
// Cannot send tokens you don't own
require(ownsAll(msg.sender, _tokenIds));
for (uint k = 0; k < _tokenIds.length; k++) {
// perform state changes necessary for transfer
_transfer(msg.sender, _to, _tokenIds[k]);
}
}
// approves the (_to) address to use the transferFrom function on the token with id (_tokenId)
// if you want to clear all approvals, simply pass the zero address
function approve(address _to, uint256 _deedId) external whenNotPaused payable {
// payable for ERC721 --> don't actually send eth @_@
require(msg.value == 0);
// use internal function?
// Cannot approve the transfer of tokens you don't own
require(owns(msg.sender, _deedId));
// Store the approval (can only approve one at a time)
partIndexToApproved[_deedId] = _to;
Approval(msg.sender, _to, _deedId);
}
// approves many token ids
function approveMany(address _to, uint256[] _tokenIds) external whenNotPaused payable {
for (uint i = 0; i < _tokenIds.length; i++) {
uint _tokenId = _tokenIds[i];
// Cannot approve the transfer of tokens you don't own
require(owns(msg.sender, _tokenId));
// Store the approval (can only approve one at a time)
partIndexToApproved[_tokenId] = _to;
//create event for each approval? _tokenId guaranteed to hold correct value?
Approval(msg.sender, _to, _tokenId);
}
}
// transfer the part with id (_tokenId) from (_from) to (_to)
// (_to) must already be approved for this (_tokenId)
function transferFrom(address _from, address _to, uint256 _tokenId) public whenNotPaused {
// Safety checks to prevent accidents
require(_to != address(0));
require(_to != address(this));
// sender must be approved
require(partIndexToApproved[_tokenId] == msg.sender);
// from must currently own the token
require(owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
// returns the current owner of the token with id = _tokenId
function ownerOf(uint256 _deedId) public view returns (address _owner) {
_owner = partIndexToOwner[_deedId];
// must result false if index key not found
require(_owner != address(0));
}
// returns a dynamic array of the ids of all tokens which are owned by (_owner)
// Looping through every possible part and checking it against the owner is
// actually much more efficient than storing a mapping or something, because
// it won't be executed as a transaction
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 totalParts = totalSupply();
return tokensOfOwnerWithinRange(_owner, 0, totalParts);
}
function tokensOfOwnerWithinRange(address _owner, uint _start, uint _numToSearch) public view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tmpResult = new uint256[](tokenCount);
if (tokenCount == 0) {
return tmpResult;
}
uint256 resultIndex = 0;
for (uint partId = _start; partId < _start + _numToSearch; partId++) {
if (partIndexToOwner[partId] == _owner) {
tmpResult[resultIndex] = partId;
resultIndex++;
if (resultIndex == tokenCount) { //found all tokens accounted for, no need to continue
break;
}
}
}
// copy number of tokens found in given range
uint resultLength = resultIndex;
uint256[] memory result = new uint256[](resultLength);
for (uint i=0; i<resultLength; i++) {
result[i] = tmpResult[i];
}
return result;
}
//same issues as above
// Returns an array of all part structs owned by the user. Free to call.
function getPartsOfOwner(address _owner) external view returns(bytes24[]) {
uint256 totalParts = totalSupply();
return getPartsOfOwnerWithinRange(_owner, 0, totalParts);
}
// This is public so it can be called by getPartsOfOwner. It should NOT be called by another contract
// as it is very gas hungry.
function getPartsOfOwnerWithinRange(address _owner, uint _start, uint _numToSearch) public view returns(bytes24[]) {
uint256 tokenCount = balanceOf(_owner);
uint resultIndex = 0;
bytes24[] memory result = new bytes24[](tokenCount);
for (uint partId = _start; partId < _start + _numToSearch; partId++) {
if (partIndexToOwner[partId] == _owner) {
result[resultIndex] = _partToBytes(parts[partId]);
resultIndex++;
}
}
return result; // will have 0 elements if tokenCount == 0
}
function _partToBytes(Part p) internal pure returns (bytes24 b) {
b = bytes24(p.tokenId);
b = b << 8;
b = b | bytes24(p.partType);
b = b << 8;
b = b | bytes24(p.partSubType);
b = b << 8;
b = b | bytes24(p.rarity);
b = b << 8;
b = b | bytes24(p.element);
b = b << 32;
b = b | bytes24(p.battlesLastDay);
b = b << 32;
b = b | bytes24(p.experience);
b = b << 32;
b = b | bytes24(p.forgeTime);
b = b << 32;
b = b | bytes24(p.battlesLastReset);
}
uint32 constant FIRST_LEVEL = 1000;
uint32 constant INCREMENT = 1000;
// every level, you need 1000 more exp to go up a level
function getLevel(uint32 _exp) public pure returns(uint32) {
uint32 c = 0;
for (uint32 i = FIRST_LEVEL; i <= FIRST_LEVEL + _exp; i += c * INCREMENT) {
c++;
}
return c;
}
string metadataBase = "https://api.etherbots.io/api/";
function setMetadataBase(string _base) external onlyOwner {
metadataBase = _base;
}
// part type, subtype,
// have one internal function which lets us implement the divergent interfaces
function _metadata(uint256 _id) internal view returns(string) {
Part memory p = parts[_id];
return strConcat(strConcat(
metadataBase,
uintToString(uint(p.partType)),
"/",
uintToString(uint(p.partSubType)),
"/"
), uintToString(uint(p.rarity)), "", "", "");
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
/// @notice A distinct URI (RFC 3986) for a given token.
/// @dev If:
/// * The URI is a URL
/// * The URL is accessible
/// * The URL points to a valid JSON file format (ECMA-404 2nd ed.)
/// * The JSON base element is an object
/// then these names of the base element SHALL have special meaning:
/// * "name": A string identifying the item to which `_deedId` grants
/// ownership
/// * "description": A string detailing the item to which `_deedId` grants
/// ownership
/// * "image": A URI pointing to a file of image/* mime type representing
/// the item to which `_deedId` grants ownership
/// Wallets and exchanges MAY display this to the end user.
/// Consider making any images at a width between 320 and 1080 pixels and
/// aspect ratio between 1.91:1 and 4:5 inclusive.
function deedUri(uint256 _deedId) external view returns (string _uri){
return _metadata(_deedId);
}
/// returns a metadata URI
function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl) {
return _metadata(_tokenId);
}
function takeOwnership(uint256 _deedId) external payable {
// payable for ERC721 --> don't actually send eth @_@
require(msg.value == 0);
address _from = partIndexToOwner[_deedId];
require(_approvedFor(msg.sender, _deedId));
_transfer(_from, msg.sender, _deedId);
}
// parts are stored sequentially
function deedByIndex(uint256 _index) external view returns (uint256 _deedId){
return _index;
}
function countOfOwners() external view returns (uint256 _count){
// TODO: implement this
return 0;
}
// thirsty function
function tokenOfOwnerByIndex(address _owner, uint _index) external view returns (uint _tokenId){
return _tokenOfOwnerByIndex(_owner, _index);
}
// code duplicated
function _tokenOfOwnerByIndex(address _owner, uint _index) private view returns (uint _tokenId){
// The index should be valid.
require(_index < balanceOf(_owner));
// can loop through all without
uint256 seen = 0;
uint256 totalTokens = totalSupply();
for (uint i = 0; i < totalTokens; i++) {
if (partIndexToOwner[i] == _owner) {
if (seen == _index) {
return i;
}
seen++;
}
}
}
function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _deedId){
return _tokenOfOwnerByIndex(_owner, _index);
}
}
// the contract which all battles must implement
// allows for different types of battles to take place
contract PerkTree is EtherbotsNFT {
// The perktree is represented in a uint8[32] representing a binary tree
// see the number of perks active
// buy a new perk
// 0: Prestige level -> starts at 0;
// next row of tree
// 1: offensive moves 2: defensive moves
// next row of tree
// 3: melee attack 4: turret shooting 5: defend arm 6: body dodge
// next row of tree
// 7: mech melee 8: android melee 9: mech turret 10: android turret
// 11: mech defence 12: android defence 13: mech body 14: android body
//next row of tree
// 15: melee electric 16: melee steel 17: melee fire 18: melee water
// 19: turret electric 20: turret steel 21: turret fire 22: turret water
// 23: defend electric 24: defend steel 25: defend fire 26: defend water
// 27: body electric 28: body steel 29: body fire 30: body water
function _leftChild(uint8 _i) internal pure returns (uint8) {
return 2*_i + 1;
}
function _rightChild(uint8 _i) internal pure returns (uint8) {
return 2*_i + 2;
}
function _parent(uint8 _i) internal pure returns (uint8) {
return (_i-1)/2;
}
uint8 constant PRESTIGE_INDEX = 0;
uint8 constant PERK_COUNT = 30;
event PrintPerk(string,uint8,uint8[32]);
function _isValidPerkToAdd(uint8[32] _perks, uint8 _index) internal pure returns (bool) {
// a previously unlocked perk is not a valid perk to add.
if ((_index==PRESTIGE_INDEX) || (_perks[_index] > 0)) {
return false;
}
// perk not valid if any ancestor not unlocked
for (uint8 i = _parent(_index); i > PRESTIGE_INDEX; i = _parent(i)) {
if (_perks[i] == 0) {
return false;
}
}
return true;
}
// sum of perks (excluding prestige)
function _sumActivePerks(uint8[32] _perks) internal pure returns (uint256) {
uint32 sum = 0;
//sum from after prestige_index, to count+1 (for prestige index).
for (uint8 i = PRESTIGE_INDEX+1; i < PERK_COUNT+1; i++) {
sum += _perks[i];
}
return sum;
}
// you can unlock a new perk every two levels (including prestige when possible)
function choosePerk(uint8 _i) external {
require((_i >= PRESTIGE_INDEX) && (_i < PERK_COUNT+1));
User storage currentUser = addressToUser[msg.sender];
uint256 _numActivePerks = _sumActivePerks(currentUser.perks);
bool canPrestige = (_numActivePerks == PERK_COUNT);
//add prestige value to sum of perks
_numActivePerks += currentUser.perks[PRESTIGE_INDEX] * PERK_COUNT;
require(_numActivePerks < getLevel(currentUser.experience) / 2);
if (_i == PRESTIGE_INDEX) {
require(canPrestige);
_prestige();
} else {
require(_isValidPerkToAdd(currentUser.perks, _i));
_addPerk(_i);
}
PerkChosen(msg.sender, _i);
}
function _addPerk(uint8 perk) internal {
addressToUser[msg.sender].perks[perk]++;
}
function _prestige() internal {
User storage currentUser = addressToUser[msg.sender];
for (uint8 i = 1; i < currentUser.perks.length; i++) {
currentUser.perks[i] = 0;
}
currentUser.perks[PRESTIGE_INDEX]++;
}
event PerkChosen(address indexed upgradedUser, uint8 indexed perk);
}
// Central collection of storage on which all other contracts depend.
// Contains structs for parts, users and functions which control their
// transferrence.
// Auction contract, facilitating statically priced sales, as well as
// inflationary and deflationary pricing for items.
// Relies heavily on the ERC721 interface and so most of the methods
// are tightly bound to that implementation
contract NFTAuctionBase is Pausable {
ERC721AllImplementations public nftContract;
uint256 public ownerCut;
uint public minDuration;
uint public maxDuration;
// Represents an auction on an NFT (in this case, Robot part)
struct Auction {
// address of part owner
address seller;
// wei price of listing
uint256 startPrice;
// wei price of floor
uint256 endPrice;
// duration of sale in seconds.
uint64 duration;
// Time when sale started
// Reset to 0 after sale concluded
uint64 start;
}
function NFTAuctionBase() public {
minDuration = 60 minutes;
maxDuration = 30 days; // arbitrary
}
// map of all tokens and their auctions
mapping (uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startPrice, uint256 endPrice, uint64 duration, uint64 start);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
// returns true if the token with id _partId is owned by the _claimant address
function _owns(address _claimant, uint256 _partId) internal view returns (bool) {
return nftContract.ownerOf(_partId) == _claimant;
}
// returns false if auction start time is 0, likely from uninitialised struct
function _isActiveAuction(Auction _auction) internal pure returns (bool) {
return _auction.start > 0;
}
// assigns ownership of the token with id = _partId to this contract
// must have already been approved
function _escrow(address, uint _partId) internal {
// throws on transfer fail
nftContract.takeOwnership(_partId);
}
// transfer the token with id = _partId to buying address
function _transfer(address _purchasor, uint256 _partId) internal {
// successful purchaseder must takeOwnership of _partId
// nftContract.approve(_purchasor, _partId);
// actual transfer
nftContract.transfer(_purchasor, _partId);
}
// creates
function _newAuction(uint256 _partId, Auction _auction) internal {
require(_auction.duration >= minDuration);
require(_auction.duration <= maxDuration);
tokenIdToAuction[_partId] = _auction;
AuctionCreated(uint256(_partId),
uint256(_auction.startPrice),
uint256(_auction.endPrice),
uint64(_auction.duration),
uint64(_auction.start)
);
}
function setMinDuration(uint _duration) external onlyOwner {
minDuration = _duration;
}
function setMaxDuration(uint _duration) external onlyOwner {
maxDuration = _duration;
}
/// Removes auction from public view, returns token to the seller
function _cancelAuction(uint256 _partId, address _seller) internal {
_removeAuction(_partId);
_transfer(_seller, _partId);
AuctionCancelled(_partId);
}
event PrintEvent(string, address, uint);
// Calculates price and transfers purchase to owner. Part is NOT transferred to buyer.
function _purchase(uint256 _partId, uint256 _purchaseAmount) internal returns (uint256) {
Auction storage auction = tokenIdToAuction[_partId];
// check that this token is being auctioned
require(_isActiveAuction(auction));
// enforce purchase >= the current price
uint256 price = _currentPrice(auction);
require(_purchaseAmount >= price);
// Store seller before we delete auction.
address seller = auction.seller;
// Valid purchase. Remove auction to prevent reentrancy.
_removeAuction(_partId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate and take fee from purchase
uint256 auctioneerCut = _computeFee(price);
uint256 sellerProceeds = price - auctioneerCut;
PrintEvent("Seller, proceeds", seller, sellerProceeds);
// Pay the seller
seller.transfer(sellerProceeds);
}
// Calculate excess funds and return to buyer.
uint256 purchaseExcess = _purchaseAmount - price;
PrintEvent("Sender, excess", msg.sender, purchaseExcess);
// Return any excess funds. Reentrancy again prevented by deleting auction.
msg.sender.transfer(purchaseExcess);
AuctionSuccessful(_partId, price, msg.sender);
return price;
}
// returns the current price of the token being auctioned in _auction
function _currentPrice(Auction storage _auction) internal view returns (uint256) {
uint256 secsElapsed = now - _auction.start;
return _computeCurrentPrice(
_auction.startPrice,
_auction.endPrice,
_auction.duration,
secsElapsed
);
}
// Checks if NFTPart is currently being auctioned.
// function _isBeingAuctioned(Auction storage _auction) internal view returns (bool) {
// return (_auction.start > 0);
// }
// removes the auction of the part with id _partId
function _removeAuction(uint256 _partId) internal {
delete tokenIdToAuction[_partId];
}
// computes the current price of an deflating-price auction
function _computeCurrentPrice( uint256 _startPrice, uint256 _endPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256 _price) {
_price = _startPrice;
if (_secondsPassed >= _duration) {
// Has been up long enough to hit endPrice.
// Return this price floor.
_price = _endPrice;
// this is a statically price sale. Just return the price.
}
else if (_duration > 0) {
// This auction contract supports auctioning from any valid price to any other valid price.
// This means the price can dynamically increase upward, or downard.
int256 priceDifference = int256(_endPrice) - int256(_startPrice);
int256 currentPriceDifference = priceDifference * int256(_secondsPassed) / int256(_duration);
int256 currentPrice = int256(_startPrice) + currentPriceDifference;
_price = uint256(currentPrice);
}
return _price;
}
// Compute percentage fee of transaction
function _computeFee (uint256 _price) internal view returns (uint256) {
return _price * ownerCut / 10000;
}
}
// Clock auction for NFTParts.
// Only timed when pricing is dynamic (i.e. startPrice != endPrice).
// Else, this becomes an infinite duration statically priced sale,
// resolving when succesfully purchase for or cancelled.
contract DutchAuction is NFTAuctionBase, EtherbotsPrivileges {
// The ERC-165 interface signature for ERC-721.
bytes4 constant InterfaceSignature_ERC721 = bytes4(0xda671b9b);
function DutchAuction(address _nftAddress, uint256 _fee) public {
require(_fee <= 10000);
ownerCut = _fee;
ERC721AllImplementations candidateContract = ERC721AllImplementations(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
nftContract = candidateContract;
}
// Remove all ether from the contract. This will be marketplace fees.
// Transfers to the NFT contract.
// Can be called by owner or NFT contract.
function withdrawBalance() external {
address nftAddress = address(nftContract);
require(msg.sender == owner || msg.sender == nftAddress);
nftAddress.transfer(this.balance);
}
event PrintEvent(string, address, uint);
// Creates an auction and lists it.
function createAuction( uint256 _partId, uint256 _startPrice, uint256 _endPrice, 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(_startPrice == uint256(uint128(_startPrice)));
require(_endPrice == uint256(uint128(_endPrice)));
require(_duration == uint256(uint64(_duration)));
require(_startPrice >= _endPrice);
require(msg.sender == address(nftContract));
_escrow(_seller, _partId);
Auction memory auction = Auction(
_seller,
uint128(_startPrice),
uint128(_endPrice),
uint64(_duration),
uint64(now) //seconds uint
);
PrintEvent("Auction Start", 0x0, auction.start);
_newAuction(_partId, auction);
}
// SCRAPYARD PRICING LOGIC
uint8 constant LAST_CONSIDERED = 5;
uint8 public scrapCounter = 0;
uint[5] public lastScrapPrices;
// Purchases an open auction
// Will transfer ownership if successful.
function purchase(uint256 _partId) external payable whenNotPaused {
address seller = tokenIdToAuction[_partId].seller;
// _purchase will throw if the purchase or funds transfer fails
uint256 price = _purchase(_partId, msg.value);
_transfer(msg.sender, _partId);
// If the seller is the scrapyard, track price information.
if (seller == address(nftContract)) {
lastScrapPrices[scrapCounter] = price;
if (scrapCounter == LAST_CONSIDERED - 1) {
scrapCounter = 0;
} else {
scrapCounter++;
}
}
}
function averageScrapPrice() public view returns (uint) {
uint sum = 0;
for (uint8 i = 0; i < LAST_CONSIDERED; i++) {
sum += lastScrapPrices[i];
}
return sum / LAST_CONSIDERED;
}
// Allows a user to cancel an auction before it's resolved.
// Returns the part to the seller.
function cancelAuction(uint256 _partId) external {
Auction storage auction = tokenIdToAuction[_partId];
require(_isActiveAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_partId, seller);
}
// returns the current price of the auction of a token with id _partId
function getCurrentPrice(uint256 _partId) external view returns (uint256) {
Auction storage auction = tokenIdToAuction[_partId];
require(_isActiveAuction(auction));
return _currentPrice(auction);
}
// Returns the details of an auction from its _partId.
function getAuction(uint256 _partId) external view returns ( address seller, uint256 startPrice, uint256 endPrice, uint256 duration, uint256 startedAt ) {
Auction storage auction = tokenIdToAuction[_partId];
require(_isActiveAuction(auction));
return ( auction.seller, auction.startPrice, auction.endPrice, auction.duration, auction.start);
}
// Allows owner to cancel an auction.
// ONLY able to be used when contract is paused,
// in the case of emergencies.
// Parts returned to seller as it's equivalent to them
// calling cancel.
function cancelAuctionWhenPaused(uint256 _partId) whenPaused onlyOwner external {
Auction storage auction = tokenIdToAuction[_partId];
require(_isActiveAuction(auction));
_cancelAuction(_partId, auction.seller);
}
}
contract EtherbotsAuction is PerkTree {
// Sets the reference to the sale auction.
function setAuctionAddress(address _address) external onlyOwner {
require(_address != address(0));
DutchAuction candidateContract = DutchAuction(_address);
// Set the new contract address
auction = candidateContract;
}
// list a part for auction.
function createAuction(
uint256 _partId,
uint256 _startPrice,
uint256 _endPrice,
uint256 _duration ) external whenNotPaused
{
// user must have current control of the part
// will lose control if they delegate to the auction
// therefore no duplicate auctions!
require(owns(msg.sender, _partId));
_approve(_partId, auction);
// will throw if inputs are invalid
// will clear transfer approval
DutchAuction(auction).createAuction(_partId,_startPrice,_endPrice,_duration,msg.sender);
}
// transfer balance back to core contract
function withdrawAuctionBalance() external onlyOwner {
DutchAuction(auction).withdrawBalance();
}
// SCRAP FUNCTION
// This takes scrapped parts and automatically relists them on the market.
// Provides a good floor for entrance into the game, while keeping supply
// constant as these parts were already in circulation.
// uint public constant SCRAPYARD_STARTING_PRICE = 0.1 ether;
uint scrapMinStartPrice = 0.05 ether; // settable minimum starting price for sanity
uint scrapMinEndPrice = 0.005 ether; // settable minimum ending price for sanity
uint scrapAuctionDuration = 2 days;
function setScrapMinStartPrice(uint _newMinStartPrice) external onlyOwner {
scrapMinStartPrice = _newMinStartPrice;
}
function setScrapMinEndPrice(uint _newMinEndPrice) external onlyOwner {
scrapMinEndPrice = _newMinEndPrice;
}
function setScrapAuctionDuration(uint _newScrapAuctionDuration) external onlyOwner {
scrapAuctionDuration = _newScrapAuctionDuration;
}
function _createScrapPartAuction(uint _scrapPartId) internal {
// if (scrapyard == address(this)) {
_approve(_scrapPartId, auction);
DutchAuction(auction).createAuction(
_scrapPartId,
_getNextAuctionPrice(), // gen next auction price
scrapMinEndPrice,
scrapAuctionDuration,
address(this)
);
// }
}
function _getNextAuctionPrice() internal view returns (uint) {
uint avg = DutchAuction(auction).averageScrapPrice();
// add 30% to the average
// prevent runaway pricing
uint next = avg + ((30 * avg) / 100);
if (next < scrapMinStartPrice) {
next = scrapMinStartPrice;
}
return next;
}
}
contract PerksRewards is EtherbotsAuction {
/// An internal method that creates a new part 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 Forge event
/// and a Transfer event.
function _createPart(uint8[4] _partArray, address _owner) internal returns (uint) {
uint32 newPartId = uint32(parts.length);
assert(newPartId == parts.length);
Part memory _part = Part({
tokenId: newPartId,
partType: _partArray[0],
partSubType: _partArray[1],
rarity: _partArray[2],
element: _partArray[3],
battlesLastDay: 0,
experience: 0,
forgeTime: uint32(now),
battlesLastReset: uint32(now)
});
assert(newPartId == parts.push(_part) - 1);
// emit the FORGING!!!
Forge(_owner, newPartId, _part);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newPartId);
return newPartId;
}
uint public PART_REWARD_CHANCE = 995;
// Deprecated subtypes contain the subtype IDs of legacy items
// which are no longer available to be redeemed in game.
// i.e. subtype ID 14 represents lambo body, presale exclusive.
// a value of 0 represents that subtype (id within range)
// as being deprecated for that part type (body, turret, etc)
uint8[] public defenceElementBySubtypeIndex;
uint8[] public meleeElementBySubtypeIndex;
uint8[] public bodyElementBySubtypeIndex;
uint8[] public turretElementBySubtypeIndex;
// uint8[] public defenceElementBySubtypeIndex = [1,2,4,3,4,1,3,3,2,1,4];
// uint8[] public meleeElementBySubtypeIndex = [3,1,3,2,3,4,2,2,1,1,1,1,4,4];
// uint8[] public bodyElementBySubtypeIndex = [2,1,2,3,4,3,1,1,4,2,3,4,1,0,1]; // no more lambos :'(
// uint8[] public turretElementBySubtypeIndex = [4,3,2,1,2,1,1,3,4,3,4];
function setRewardChance(uint _newChance) external onlyOwner {
require(_newChance > 980); // not too hot
require(_newChance <= 1000); // not too cold
PART_REWARD_CHANCE = _newChance; // just right
// come at me goldilocks
}
// The following functions DON'T create parts, they add new parts
// as possible rewards from the reward pool.
function addDefenceParts(uint8[] _newElement) external onlyOwner {
for (uint8 i = 0; i < _newElement.length; i++) {
defenceElementBySubtypeIndex.push(_newElement[i]);
}
// require(defenceElementBySubtypeIndex.length < uint(uint8(-1)));
}
function addMeleeParts(uint8[] _newElement) external onlyOwner {
for (uint8 i = 0; i < _newElement.length; i++) {
meleeElementBySubtypeIndex.push(_newElement[i]);
}
// require(meleeElementBySubtypeIndex.length < uint(uint8(-1)));
}
function addBodyParts(uint8[] _newElement) external onlyOwner {
for (uint8 i = 0; i < _newElement.length; i++) {
bodyElementBySubtypeIndex.push(_newElement[i]);
}
// require(bodyElementBySubtypeIndex.length < uint(uint8(-1)));
}
function addTurretParts(uint8[] _newElement) external onlyOwner {
for (uint8 i = 0; i < _newElement.length; i++) {
turretElementBySubtypeIndex.push(_newElement[i]);
}
// require(turretElementBySubtypeIndex.length < uint(uint8(-1)));
}
// Deprecate subtypes. Once a subtype has been deprecated it can never be
// undeprecated. Starting with lambo!
function deprecateDefenceSubtype(uint8 _subtypeIndexToDeprecate) external onlyOwner {
defenceElementBySubtypeIndex[_subtypeIndexToDeprecate] = 0;
}
function deprecateMeleeSubtype(uint8 _subtypeIndexToDeprecate) external onlyOwner {
meleeElementBySubtypeIndex[_subtypeIndexToDeprecate] = 0;
}
function deprecateBodySubtype(uint8 _subtypeIndexToDeprecate) external onlyOwner {
bodyElementBySubtypeIndex[_subtypeIndexToDeprecate] = 0;
}
function deprecateTurretSubtype(uint8 _subtypeIndexToDeprecate) external onlyOwner {
turretElementBySubtypeIndex[_subtypeIndexToDeprecate] = 0;
}
// function _randomIndex(uint _rand, uint8 _startIx, uint8 _endIx, uint8 _modulo) internal pure returns (uint8) {
// require(_startIx < _endIx);
// bytes32 randBytes = bytes32(_rand);
// uint result = 0;
// for (uint8 i=_startIx; i<_endIx; i++) {
// result = result | uint8(randBytes[i]);
// result << 8;
// }
// uint8 resultInt = uint8(uint(result) % _modulo);
// return resultInt;
// }
// This function takes a random uint, an owner and randomly generates a valid part.
// It then transfers that part to the owner.
function _generateRandomPart(uint _rand, address _owner) internal {
// random uint 20 in length - MAYBE 20.
// first randomly gen a part type
_rand = uint(keccak256(_rand));
uint8[4] memory randomPart;
randomPart[0] = uint8(_rand % 4) + 1;
_rand = uint(keccak256(_rand));
// randomPart[0] = _randomIndex(_rand,0,4,4) + 1; // 1, 2, 3, 4, => defence, melee, body, turret
if (randomPart[0] == DEFENCE) {
randomPart[1] = _getRandomPartSubtype(_rand,defenceElementBySubtypeIndex);
randomPart[3] = _getElement(defenceElementBySubtypeIndex, randomPart[1]);
} else if (randomPart[0] == MELEE) {
randomPart[1] = _getRandomPartSubtype(_rand,meleeElementBySubtypeIndex);
randomPart[3] = _getElement(meleeElementBySubtypeIndex, randomPart[1]);
} else if (randomPart[0] == BODY) {
randomPart[1] = _getRandomPartSubtype(_rand,bodyElementBySubtypeIndex);
randomPart[3] = _getElement(bodyElementBySubtypeIndex, randomPart[1]);
} else if (randomPart[0] == TURRET) {
randomPart[1] = _getRandomPartSubtype(_rand,turretElementBySubtypeIndex);
randomPart[3] = _getElement(turretElementBySubtypeIndex, randomPart[1]);
}
_rand = uint(keccak256(_rand));
randomPart[2] = _getRarity(_rand);
// randomPart[2] = _getRarity(_randomIndex(_rand,8,12,3)); // rarity
_createPart(randomPart, _owner);
}
function _getRandomPartSubtype(uint _rand, uint8[] elementBySubtypeIndex) internal pure returns (uint8) {
require(elementBySubtypeIndex.length < uint(uint8(-1)));
uint8 subtypeLength = uint8(elementBySubtypeIndex.length);
require(subtypeLength > 0);
uint8 subtypeIndex = uint8(_rand % subtypeLength);
// uint8 subtypeIndex = _randomIndex(_rand,4,8,subtypeLength);
uint8 count = 0;
while (elementBySubtypeIndex[subtypeIndex] == 0) {
subtypeIndex++;
count++;
if (subtypeIndex == subtypeLength) {
subtypeIndex = 0;
}
if (count > subtypeLength) {
break;
}
}
require(elementBySubtypeIndex[subtypeIndex] != 0);
return subtypeIndex + 1;
}
function _getRarity(uint rand) pure internal returns (uint8) {
uint16 rarity = uint16(rand % 1000);
if (rarity >= 990) { // 1% chance of gold
return GOLD;
} else if (rarity >= 970) { // 2% chance of shadow
return SHADOW;
} else {
return STANDARD;
}
}
function _getElement(uint8[] elementBySubtypeIndex, uint8 subtype) internal pure returns (uint8) {
uint8 subtypeIndex = subtype - 1;
return elementBySubtypeIndex[subtypeIndex];
}
mapping(address => uint[]) pendingPartCrates ;
function getPendingPartCrateLength() external view returns (uint) {
return pendingPartCrates[msg.sender].length;
}
/// Put shards together into a new part-crate
function redeemShardsIntoPending() external {
User storage user = addressToUser[msg.sender];
while (user.numShards >= SHARDS_TO_PART) {
user.numShards -= SHARDS_TO_PART;
pendingPartCrates[msg.sender].push(block.number);
// 256 blocks to redeem
}
}
function openPendingPartCrates() external {
uint[] memory crates = pendingPartCrates[msg.sender];
for (uint i = 0; i < crates.length; i++) {
uint pendingBlockNumber = crates[i];
// can't open on the same timestamp
require(block.number > pendingBlockNumber);
var hash = block.blockhash(pendingBlockNumber);
if (uint(hash) != 0) {
// different results for all different crates, even on the same block/same user
// randomness is already taken care of
uint rand = uint(keccak256(hash, msg.sender, i)); // % (10 ** 20);
_generateRandomPart(rand, msg.sender);
} else {
// Do nothing, no second chances to secure integrity of randomness.
}
}
delete pendingPartCrates[msg.sender];
}
uint32 constant SHARDS_MAX = 10000;
function _addShardsToUser(User storage _user, uint32 _shards) internal {
uint32 updatedShards = _user.numShards + _shards;
if (updatedShards > SHARDS_MAX) {
updatedShards = SHARDS_MAX;
}
_user.numShards = updatedShards;
ShardsAdded(msg.sender, _shards);
}
// FORGING / SCRAPPING
event ShardsAdded(address caller, uint32 shards);
event Scrap(address user, uint partId);
uint32 constant SHARDS_TO_PART = 500;
uint8 public scrapPercent = 60;
uint8 public burnRate = 60;
function setScrapPercent(uint8 _newPercent) external onlyOwner {
require((_newPercent >= 50) && (_newPercent <= 90));
scrapPercent = _newPercent;
}
// function setScrapyard(address _scrapyard) external onlyOwner {
// scrapyard = _scrapyard;
// }
function setBurnRate(uint8 _rate) external onlyOwner {
burnRate = _rate;
}
uint public scrapCount = 0;
// scraps a part for shards
function scrap(uint partId) external {
require(owns(msg.sender, partId));
User storage u = addressToUser[msg.sender];
_addShardsToUser(u, (SHARDS_TO_PART * scrapPercent) / 100);
Scrap(msg.sender, partId);
// this doesn't need to be secure
// no way to manipulate it apart from guaranteeing your parts are resold
// or burnt
if (uint(keccak256(scrapCount)) % 100 >= burnRate) {
_transfer(msg.sender, address(this), partId);
_createScrapPartAuction(partId);
} else {
_transfer(msg.sender, address(0), partId);
}
scrapCount++;
}
}
contract Mint is PerksRewards {
// Owner only function to give an address new parts.
// Strictly capped at 5000.
// This will ONLY be used for promotional purposes (i.e. providing items for Wax/OPSkins partnership)
// which we don't benefit financially from, or giving users who win the prize of designing a part
// for the game, a single copy of that part.
uint16 constant MINT_LIMIT = 5000;
uint16 public partsMinted = 0;
function mintParts(uint16 _count, address _owner) public onlyOwner {
require(_count > 0 && _count <= 50);
// check overflow
require(partsMinted + _count > partsMinted);
require(partsMinted + _count < MINT_LIMIT);
addressToUser[_owner].numShards += SHARDS_TO_PART * _count;
partsMinted += _count;
}
function mintParticularPart(uint8[4] _partArray, address _owner) public onlyOwner {
require(partsMinted < MINT_LIMIT);
/* cannot create deprecated parts
for (uint i = 0; i < deprecated.length; i++) {
if (_partArray[2] == deprecated[i]) {
revert();
}
} */
_createPart(_partArray, _owner);
partsMinted++;
}
}
contract NewCratePreSale {
// migration functions migrate the data from the previous contract in stages
// all addresses are included for transparency and easy verification
// however addresses with no robots (i.e. failed transaction and never bought properly) have been commented out.
// to view the full list of state assignments, go to etherscan.io/address/{address} and you can view the verified
mapping (address => uint[]) public userToRobots;
function _migrate(uint _index) external onlyOwner {
bytes4 selector = bytes4(keccak256("setData()"));
address a = migrators[_index];
require(a.delegatecall(selector));
}
// source code - feel free to verify the migration
address[6] migrators = [
0x700FeBD9360ac0A0a72F371615427Bec4E4454E5, //0x97AE01893E42d6d33fd9851A28E5627222Af7BBB,
0x72Cc898de0A4EAC49c46ccb990379099461342f6,
0xc3cC48da3B8168154e0f14Bf0446C7a93613F0A7,
0x4cC96f2Ddf6844323ae0d8461d418a4D473b9AC3,
0xa52bFcb5FF599e29EE2B9130F1575BaBaa27de0A,
0xe503b42AabdA22974e2A8B75Fa87E010e1B13584
];
function NewCratePreSale() public payable {
owner = msg.sender;
// one time transfer of state from the previous contract
// var previous = CratePreSale(0x3c7767011C443EfeF2187cf1F2a4c02062da3998); //MAINNET
// oldAppreciationRateWei = previous.appreciationRateWei();
oldAppreciationRateWei = 100000000000000;
appreciationRateWei = oldAppreciationRateWei;
// oldPrice = previous.currentPrice();
oldPrice = 232600000000000000;
currentPrice = oldPrice;
// oldCratesSold = previous.cratesSold();
oldCratesSold = 1075;
cratesSold = oldCratesSold;
// Migration Rationale
// due to solidity issues with enumerability (contract calls cannot return dynamic arrays etc)
// no need for trust -> can still use web3 to call the previous contract and check the state
// will only change in the future if people send more eth
// and will be obvious due to change in crate count. Any purchases on the old contract
// after this contract is deployed will be fully refunded, and those robots bought will be voided.
// feel free to validate any address on the old etherscan:
// https://etherscan.io/address/0x3c7767011C443EfeF2187cf1F2a4c02062da3998
// can visit the exact contracts at the addresses listed above
}
// ------ STATE ------
uint256 constant public MAX_CRATES_TO_SELL = 3900; // Max no. of robot crates to ever be sold
uint256 constant public PRESALE_END_TIMESTAMP = 1518699600; // End date for the presale - no purchases can be made after this date - Midnight 16 Feb 2018 UTC
uint256 public appreciationRateWei;
uint32 public cratesSold;
uint256 public currentPrice;
// preserve these for later verification
uint32 public oldCratesSold;
uint256 public oldPrice;
uint256 public oldAppreciationRateWei;
// mapping (address => uint32) public userCrateCount; // replaced with more efficient method
// store the unopened crates of this user
// actually stores the blocknumber of each crate
mapping (address => uint[]) public addressToPurchasedBlocks;
// store the number of expired crates for each user
// i.e. crates where the user failed to open the crate within 256 blocks (~1 hour)
// these crates will be able to be opened post-launch
mapping (address => uint) public expiredCrates;
// store the part information of purchased crates
function openAll() public {
uint len = addressToPurchasedBlocks[msg.sender].length;
require(len > 0);
uint8 count = 0;
// len > i to stop predicatable wraparound
for (uint i = len - 1; i >= 0 && len > i; i--) {
uint crateBlock = addressToPurchasedBlocks[msg.sender][i];
require(block.number > crateBlock);
// can't open on the same timestamp
var hash = block.blockhash(crateBlock);
if (uint(hash) != 0) {
// different results for all different crates, even on the same block/same user
// randomness is already taken care of
uint rand = uint(keccak256(hash, msg.sender, i)) % (10 ** 20);
userToRobots[msg.sender].push(rand);
count++;
} else {
// all others will be expired
expiredCrates[msg.sender] += (i + 1);
break;
}
}
CratesOpened(msg.sender, count);
delete addressToPurchasedBlocks[msg.sender];
}
// ------ EVENTS ------
event CratesPurchased(address indexed _from, uint8 _quantity);
event CratesOpened(address indexed _from, uint8 _quantity);
// ------ FUNCTIONS ------
function getPrice() view public returns (uint256) {
return currentPrice;
}
function getRobotCountForUser(address _user) external view returns(uint256) {
return userToRobots[_user].length;
}
function getRobotForUserByIndex(address _user, uint _index) external view returns(uint) {
return userToRobots[_user][_index];
}
function getRobotsForUser(address _user) view public returns (uint[]) {
return userToRobots[_user];
}
function getPendingCratesForUser(address _user) external view returns(uint[]) {
return addressToPurchasedBlocks[_user];
}
function getPendingCrateForUserByIndex(address _user, uint _index) external view returns(uint) {
return addressToPurchasedBlocks[_user][_index];
}
function getExpiredCratesForUser(address _user) external view returns(uint) {
return expiredCrates[_user];
}
function incrementPrice() private {
// Decrease the rate of increase of the crate price
// as the crates become more expensive
// to avoid runaway pricing
// (halving rate of increase at 0.1 ETH, 0.2 ETH, 0.3 ETH).
if ( currentPrice == 100000000000000000 ) {
appreciationRateWei = 200000000000000;
} else if ( currentPrice == 200000000000000000) {
appreciationRateWei = 100000000000000;
} else if (currentPrice == 300000000000000000) {
appreciationRateWei = 50000000000000;
}
currentPrice += appreciationRateWei;
}
function purchaseCrates(uint8 _cratesToBuy) public payable whenNotPaused {
require(now < PRESALE_END_TIMESTAMP); // Check presale is still ongoing.
require(_cratesToBuy <= 10); // Can only buy max 10 crates at a time. Don't be greedy!
require(_cratesToBuy >= 1); // Sanity check. Also, you have to buy a crate.
require(cratesSold + _cratesToBuy <= MAX_CRATES_TO_SELL); // Check max crates sold is less than hard limit
uint256 priceToPay = _calculatePayment(_cratesToBuy);
require(msg.value >= priceToPay); // Check buyer sent sufficient funds to purchase
if (msg.value > priceToPay) { //overpaid, return excess
msg.sender.transfer(msg.value-priceToPay);
}
//all good, payment received. increment number sold, price, and generate crate receipts!
cratesSold += _cratesToBuy;
for (uint8 i = 0; i < _cratesToBuy; i++) {
incrementPrice();
addressToPurchasedBlocks[msg.sender].push(block.number);
}
CratesPurchased(msg.sender, _cratesToBuy);
}
function _calculatePayment (uint8 _cratesToBuy) private view returns (uint256) {
uint256 tempPrice = currentPrice;
for (uint8 i = 1; i < _cratesToBuy; i++) {
tempPrice += (currentPrice + (appreciationRateWei * i));
} // for every crate over 1 bought, add current Price and a multiple of the appreciation rate
// very small edge case of buying 10 when you the appreciation rate is about to halve
// is compensated by the great reduction in gas by buying N at a time.
return tempPrice;
}
//owner only withdrawal function for the presale
function withdraw() onlyOwner public {
owner.transfer(this.balance);
}
function addFunds() onlyOwner external payable {
}
event SetPaused(bool paused);
// starts unpaused
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() external onlyOwner whenNotPaused returns (bool) {
paused = true;
SetPaused(paused);
return true;
}
function unpause() external onlyOwner whenPaused returns (bool) {
paused = false;
SetPaused(paused);
return true;
}
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract EtherbotsMigrations is Mint {
event CratesOpened(address indexed _from, uint8 _quantity);
event OpenedOldCrates(address indexed _from);
event MigratedCrates(address indexed _from, uint16 _quantity, bool isMigrationComplete);
address presale = 0xc23F76aEa00B775AADC8504CcB22468F4fD2261A;
mapping(address => bool) public hasMigrated;
mapping(address => bool) public hasOpenedOldCrates;
mapping(address => uint[]) pendingCrates;
mapping(address => uint16) public cratesMigrated;
// Element: copy for MIGRATIONS ONLY.
string constant private DEFENCE_ELEMENT_BY_ID = "12434133214";
string constant private MELEE_ELEMENT_BY_ID = "31323422111144";
string constant private BODY_ELEMENT_BY_ID = "212343114234111";
string constant private TURRET_ELEMENT_BY_ID = "43212113434";
// Once only function.
// Transfers all pending and expired crates in the old contract
// into pending crates in the current one.
// Users can then open them on the new contract.
// Should only rarely have to be called.
// event oldpending(uint old);
function openOldCrates() external {
require(hasOpenedOldCrates[msg.sender] == false);
// uint oldPendingCrates = NewCratePreSale(presale).getPendingCrateForUserByIndex(msg.sender,0); // getting unrecognised opcode here --!
// oldpending(oldPendingCrates);
// require(oldPendingCrates == 0);
_migrateExpiredCrates();
hasOpenedOldCrates[msg.sender] = true;
OpenedOldCrates(msg.sender);
}
function migrate() external whenNotPaused {
// Can't migrate twice .
require(hasMigrated[msg.sender] == false);
// require(NewCratePreSale(presale).getPendingCrateForUserByIndex(msg.sender,0) == 0);
// No pending crates in the new contract allowed. Make sure you open them first.
require(pendingCrates[msg.sender].length == 0);
// If the user has old expired crates, don't let them migrate until they've
// converted them to pending crates in the new contract.
if (NewCratePreSale(presale).getExpiredCratesForUser(msg.sender) > 0) {
require(hasOpenedOldCrates[msg.sender]);
}
// have to make a ton of calls unfortunately
uint16 length = uint16(NewCratePreSale(presale).getRobotCountForUser(msg.sender));
// gas limit will be exceeded with *whale* etherbot players!
// let's migrate their robots in batches of ten.
// they can afford it
bool isMigrationComplete = false;
var max = length - cratesMigrated[msg.sender];
if (max > 9) {
max = 9;
} else { // final call - all robots will be migrated
isMigrationComplete = true;
hasMigrated[msg.sender] = true;
}
for (uint i = cratesMigrated[msg.sender]; i < cratesMigrated[msg.sender] + max; i++) {
var robot = NewCratePreSale(presale).getRobotForUserByIndex(msg.sender, i);
var robotString = uintToString(robot);
// MigratedBot(robotString);
_migrateRobot(robotString);
}
cratesMigrated[msg.sender] += max;
MigratedCrates(msg.sender, cratesMigrated[msg.sender], isMigrationComplete);
}
function _migrateRobot(string robot) private {
var (melee, defence, body, turret) = _convertBlueprint(robot);
// blueprints event
// blueprints(body, turret, melee, defence);
_createPart(melee, msg.sender);
_createPart(defence, msg.sender);
_createPart(turret, msg.sender);
_createPart(body, msg.sender);
}
function _getRarity(string original, uint8 low, uint8 high) pure private returns (uint8) {
uint32 rarity = stringToUint32(substring(original,low,high));
if (rarity >= 950) {
return GOLD;
} else if (rarity >= 850) {
return SHADOW;
} else {
return STANDARD;
}
}
function _getElement(string elementString, uint partId) pure private returns(uint8) {
return stringToUint8(substring(elementString, partId-1,partId));
}
// Actually part type
function _getPartId(string original, uint8 start, uint8 end, uint8 partCount) pure private returns(uint8) {
return (stringToUint8(substring(original,start,end)) % partCount) + 1;
}
function userPendingCrateNumber(address _user) external view returns (uint) {
return pendingCrates[_user].length;
}
// convert old string representation of robot into 4 new ERC721 parts
function _convertBlueprint(string original) pure private returns(uint8[4] body,uint8[4] melee, uint8[4] turret, uint8[4] defence ) {
/* ------ CONVERSION TIME ------ */
body[0] = BODY;
body[1] = _getPartId(original, 3, 5, 15);
body[2] = _getRarity(original, 0, 3);
body[3] = _getElement(BODY_ELEMENT_BY_ID, body[1]);
turret[0] = TURRET;
turret[1] = _getPartId(original, 8, 10, 11);
turret[2] = _getRarity(original, 5, 8);
turret[3] = _getElement(TURRET_ELEMENT_BY_ID, turret[1]);
melee[0] = MELEE;
melee[1] = _getPartId(original, 13, 15, 14);
melee[2] = _getRarity(original, 10, 13);
melee[3] = _getElement(MELEE_ELEMENT_BY_ID, melee[1]);
defence[0] = DEFENCE;
var len = bytes(original).length;
// string of number does not have preceding 0's
if (len == 20) {
defence[1] = _getPartId(original, 18, 20, 11);
} else if (len == 19) {
defence[1] = _getPartId(original, 18, 19, 11);
} else { //unlikely to have length less than 19
defence[1] = uint8(1);
}
defence[2] = _getRarity(original, 15, 18);
defence[3] = _getElement(DEFENCE_ELEMENT_BY_ID, defence[1]);
// implicit return
}
// give one more chance
function _migrateExpiredCrates() private {
// get the number of expired crates
uint expired = NewCratePreSale(presale).getExpiredCratesForUser(msg.sender);
for (uint i = 0; i < expired; i++) {
pendingCrates[msg.sender].push(block.number);
}
}
// Users can open pending crates on the new contract.
function openCrates() public whenNotPaused {
uint[] memory pc = pendingCrates[msg.sender];
require(pc.length > 0);
uint8 count = 0;
for (uint i = 0; i < pc.length; i++) {
uint crateBlock = pc[i];
require(block.number > crateBlock);
// can't open on the same timestamp
var hash = block.blockhash(crateBlock);
if (uint(hash) != 0) {
// different results for all different crates, even on the same block/same user
// randomness is already taken care of
uint rand = uint(keccak256(hash, msg.sender, i)) % (10 ** 20);
_migrateRobot(uintToString(rand));
count++;
}
}
CratesOpened(msg.sender, count);
delete pendingCrates[msg.sender];
}
}
contract Battle {
// This struct does not exist outside the context of a battle
// the name of the battle type
function name() external view returns (string);
// the number of robots currently battling
function playerCount() external view returns (uint count);
// creates a new battle, with a submitted user string for initial input/
function createBattle(address _creator, uint[] _partIds, bytes32 _commit, uint _revealLength) external payable returns (uint);
// cancels the battle at battleID
function cancelBattle(uint battleID) external;
function winnerOf(uint battleId, uint index) external view returns (address);
function loserOf(uint battleId, uint index) external view returns (address);
event BattleCreated(uint indexed battleID, address indexed starter);
event BattleStage(uint indexed battleID, uint8 moveNumber, uint8[2] attackerMovesDefenderMoves, uint16[2] attackerDamageDefenderDamage);
event BattleEnded(uint indexed battleID, address indexed winner);
event BattleConcluded(uint indexed battleID);
event BattlePropertyChanged(string name, uint previous, uint value);
}
contract EtherbotsBattle is EtherbotsMigrations {
// can never remove any of these contracts, can only add
// once we publish a contract, you'll always be able to play by that ruleset
// good for two player games which are non-susceptible to collusion
// people can be trusted to choose the most beneficial outcome, which in this case
// is the fairest form of gameplay.
// fields which are vulnerable to collusion still have to be centrally controlled :(
function addApprovedBattle(Battle _battle) external onlyOwner {
approvedBattles.push(_battle);
}
function _isApprovedBattle() internal view returns (bool) {
for (uint8 i = 0; i < approvedBattles.length; i++) {
if (msg.sender == address(approvedBattles[i])) {
return true;
}
}
return false;
}
modifier onlyApprovedBattles(){
require(_isApprovedBattle());
_;
}
function createBattle(uint _battleId, uint[] partIds, bytes32 commit, uint revealLength) external payable {
// sanity check to make sure _battleId is a valid battle
require(_battleId < approvedBattles.length);
//if parts are given, make sure they are owned
if (partIds.length > 0) {
require(ownsAll(msg.sender, partIds));
}
//battle can decide number of parts required for battle
Battle battle = Battle(approvedBattles[_battleId]);
// Transfer all to selected battle contract.
for (uint i=0; i<partIds.length; i++) {
_approve(partIds[i], address(battle));
}
uint newDuelId = battle.createBattle.value(msg.value)(msg.sender, partIds, commit, revealLength);
NewDuel(_battleId, newDuelId);
}
event NewDuel(uint battleId, uint duelId);
mapping(address => Reward[]) public pendingRewards;
// actually probably just want a length getter here as default public mapping getters
// are pretty expensive
function getPendingBattleRewardsCount(address _user) external view returns (uint) {
return pendingRewards[_user].length;
}
struct Reward {
uint blocknumber;
int32 exp;
}
function addExperience(address _user, uint[] _partIds, int32[] _exps) external onlyApprovedBattles {
address user = _user;
require(_partIds.length == _exps.length);
int32 sum = 0;
for (uint i = 0; i < _exps.length; i++) {
sum += _addPartExperience(_partIds[i], _exps[i]);
}
_addUserExperience(user, sum);
_storeReward(user, sum);
}
// store sum.
function _storeReward(address _user, int32 _battleExp) internal {
pendingRewards[_user].push(Reward({
blocknumber: 0,
exp: _battleExp
}));
}
/* function _getExpProportion(int _exp) returns(int) {
// assume max/min of 1k, -1k
return 1000 + _exp + 1; // makes it between (1, 2001)
} */
uint8 bestMultiple = 3;
uint8 mediumMultiple = 2;
uint8 worstMultiple = 1;
uint8 minShards = 1;
uint8 bestProbability = 97;
uint8 mediumProbability = 85;
function _getExpMultiple(int _exp) internal view returns (uint8, uint8) {
if (_exp > 500) {
return (bestMultiple,mediumMultiple);
} else if (_exp > 0) {
return (mediumMultiple,mediumMultiple);
} else {
return (worstMultiple,mediumMultiple);
}
}
function setBest(uint8 _newBestMultiple) external onlyOwner {
bestMultiple = _newBestMultiple;
}
function setMedium(uint8 _newMediumMultiple) external onlyOwner {
mediumMultiple = _newMediumMultiple;
}
function setWorst(uint8 _newWorstMultiple) external onlyOwner {
worstMultiple = _newWorstMultiple;
}
function setMinShards(uint8 _newMin) external onlyOwner {
minShards = _newMin;
}
function setBestProbability(uint8 _newBestProb) external onlyOwner {
bestProbability = _newBestProb;
}
function setMediumProbability(uint8 _newMinProb) external onlyOwner {
mediumProbability = _newMinProb;
}
function _calculateShards(int _exp, uint rand) internal view returns (uint16) {
var (a, b) = _getExpMultiple(_exp);
uint16 shards;
uint randPercent = rand % 100;
if (randPercent > bestProbability) {
shards = uint16(a * ((rand % 20) + 12) / b);
} else if (randPercent > mediumProbability) {
shards = uint16(a * ((rand % 10) + 6) / b);
} else {
shards = uint16((a * (rand % 5)) / b);
}
if (shards < minShards) {
shards = minShards;
}
return shards;
}
// convert wins into pending battle crates
// Not to pending old crates (migration), nor pending part crates (redeemShards)
function convertReward() external {
Reward[] storage rewards = pendingRewards[msg.sender];
for (uint i = 0; i < rewards.length; i++) {
if (rewards[i].blocknumber == 0) {
rewards[i].blocknumber = block.number;
}
}
}
// in PerksRewards
function redeemBattleCrates() external {
uint8 count = 0;
uint len = pendingRewards[msg.sender].length;
require(len > 0);
for (uint i = 0; i < len; i++) {
Reward memory rewardStruct = pendingRewards[msg.sender][i];
// can't open on the same timestamp
require(block.number > rewardStruct.blocknumber);
// ensure user has converted all pendingRewards
require(rewardStruct.blocknumber != 0);
var hash = block.blockhash(rewardStruct.blocknumber);
if (uint(hash) != 0) {
// different results for all different crates, even on the same block/same user
// randomness is already taken care of
uint rand = uint(keccak256(hash, msg.sender, i));
_generateBattleReward(rand,rewardStruct.exp);
count++;
} else {
// Do nothing, no second chances to secure integrity of randomness.
}
}
CratesOpened(msg.sender, count);
delete pendingRewards[msg.sender];
}
function _generateBattleReward(uint rand, int32 exp) internal {
if (((rand % 1000) > PART_REWARD_CHANCE) && (exp > 0)) {
_generateRandomPart(rand, msg.sender);
} else {
_addShardsToUser(addressToUser[msg.sender], _calculateShards(exp, rand));
}
}
// don't need to do any scaling
// should already have been done by previous stages
function _addUserExperience(address user, int32 exp) internal {
// never allow exp to drop below 0
User memory u = addressToUser[user];
if (exp < 0 && uint32(int32(u.experience) + exp) > u.experience) {
u.experience = 0;
return;
} else if (exp > 0) {
// check for overflow
require(uint32(int32(u.experience) + exp) > u.experience);
}
addressToUser[user].experience = uint32(int32(u.experience) + exp);
//_addUserReward(user, exp);
}
function setMinScaled(int8 _min) external onlyOwner {
minScaled = _min;
}
int8 minScaled = 25;
function _scaleExp(uint32 _battleCount, int32 _exp) internal view returns (int32) {
if (_battleCount <= 10) {
return _exp; // no drop off
}
int32 exp = (_exp * 10)/int32(_battleCount);
if (exp < minScaled) {
return minScaled;
}
return exp;
}
function _addPartExperience(uint _id, int32 _baseExp) internal returns (int32) {
// never allow exp to drop below 0
Part storage p = parts[_id];
if (now - p.battlesLastReset > 24 hours) {
p.battlesLastReset = uint32(now);
p.battlesLastDay = 0;
}
p.battlesLastDay++;
int32 exp = _baseExp;
if (exp > 0) {
exp = _scaleExp(p.battlesLastDay, _baseExp);
}
if (exp < 0 && uint32(int32(p.experience) + exp) > p.experience) {
// check for wrap-around
p.experience = 0;
return;
} else if (exp > 0) {
// check for overflow
require(uint32(int32(p.experience) + exp) > p.experience);
}
parts[_id].experience = uint32(int32(parts[_id].experience) + exp);
return exp;
}
function totalLevel(uint[] partIds) public view returns (uint32) {
uint32 total = 0;
for (uint i = 0; i < partIds.length; i++) {
total += getLevel(parts[partIds[i]].experience);
}
return total;
}
//requires parts in order
function hasOrderedRobotParts(uint[] partIds) external view returns(bool) {
uint len = partIds.length;
if (len != 4) {
return false;
}
for (uint i = 0; i < len; i++) {
if (parts[partIds[i]].partType != i+1) {
return false;
}
}
return true;
}
}
contract EtherbotsCore is EtherbotsBattle {
// The structure of Etherbots is modelled on CryptoKitties for obvious reasons:
// ease of implementation, tried + tested etc.
// it elides some features and includes some others.
// The full system is implemented in the following manner:
//
// EtherbotsBase | Storage and base types
// EtherbotsAccess | Access Control - who can change which state vars etc.
// EtherbotsNFT | ERC721 Implementation
// EtherbotsBattle | Battle interface contract: only one implementation currently, but could add more later.
// EtherbotsAuction | Auction interface contract
function EtherbotsCore() public {
// Starts paused.
paused = true;
owner = msg.sender;
}
function() external payable {
}
function withdrawBalance() external onlyOwner {
owner.transfer(this.balance);
}
}
| blueprints event blueprints(body, turret, melee, defence); | function _migrateRobot(string robot) private {
var (melee, defence, body, turret) = _convertBlueprint(robot);
_createPart(melee, msg.sender);
_createPart(defence, msg.sender);
_createPart(turret, msg.sender);
_createPart(body, msg.sender);
}
| 14,085,012 | [
1,
31502,
87,
871,
13712,
87,
12,
3432,
16,
268,
295,
1349,
16,
312,
292,
1340,
16,
1652,
802,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
22083,
20605,
12,
1080,
14386,
13,
3238,
288,
203,
3639,
569,
261,
81,
292,
1340,
16,
1652,
802,
16,
1417,
16,
268,
295,
1349,
13,
273,
389,
6283,
30123,
12,
28870,
1769,
203,
3639,
389,
2640,
1988,
12,
81,
292,
1340,
16,
1234,
18,
15330,
1769,
203,
3639,
389,
2640,
1988,
12,
536,
802,
16,
1234,
18,
15330,
1769,
203,
3639,
389,
2640,
1988,
12,
25271,
1349,
16,
1234,
18,
15330,
1769,
203,
3639,
389,
2640,
1988,
12,
3432,
16,
1234,
18,
15330,
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
]
|
pragma solidity ^0.4.24;
/***********************************************************
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
***********************************************************/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev 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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
/***********************************************************
* NameFilter library
***********************************************************/
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/***********************************************************
* NTech3DDatasets library
***********************************************************/
library NTech3DDatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 NTAmount; // amount distributed to nt
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
uint256 prevres; // 上一轮或者奖池互换流入本轮的奖金
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 nt; // % of buy in thats paid to nt holders
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 nt; // % of pot thats paid to NT foundation
}
}
/***********************************************************
interface : OtherNTech3D
主要用作奖池互换
***********************************************************/
interface OtherNTech3D {
function potSwap() external payable;
}
/***********************************************************
* NTech3DKeysCalcLong library
***********************************************************/
library NTech3DKeysCalcLong {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
/***********************************************************
* ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
***********************************************************/
contract ERC20 {
function totalSupply() public view returns (uint supply);
function balanceOf( address who ) public view returns (uint value);
function allowance( address owner, address spender ) public view returns (uint _allowance);
function transfer( address to, uint value) public returns (bool ok);
function transferFrom( address from, address to, uint value) public returns (bool ok);
function approve( address spender, uint value ) public returns (bool ok);
event Transfer( address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
}
/***********************************************************
interface : PlayerBookInterface
***********************************************************/
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
/***********************************************************
* NTech3DLong contract
***********************************************************/
contract NTech3DLong {
/******************************************************************************************
导入的库
*/
using SafeMath for *;
using NameFilter for string;
using NTech3DKeysCalcLong for uint256;
/******************************************************************************************
事件
*/
// 当玩家注册名字时调用
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// 购买完成后或者再次载入时调用
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 NTAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// 撤退时调用
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// 当撤退并且分发时调用
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 NTAmount,
uint256 genAmount
);
// 当一轮时间过后,有玩家试图购买时调用
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 NTAmount,
uint256 genAmount
);
//当一轮时间过后,有玩家重载时调用
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 NTAmount,
uint256 genAmount
);
// 附属账号有支付时调用
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
// 收到奖池存款调用
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
/******************************************************************************************
合约权限管理
设计:会设计用户权限管理,
9 => 管理员角色
0 => 没有任何权限
*/
// 用户地址到角色的表
mapping(address => uint256) private users ;
// 初始化
function initUsers() private {
// 初始化下列地址帐户为管理员
users[0x89b2E7Ee504afd522E07F80Ae7b9d4D228AF3fe2] = 9 ;
users[msg.sender] = 9 ;
}
// 是否是管理员
modifier isAdmin() {
uint256 role = users[msg.sender];
require((role==9), "Must be admin.");
_;
}
/******************************************************************************************
检查是帐户地址还是合约地址
*/
modifier isHuman {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "Humans only");
_;
}
/******************************************************************************************
关联合约定义
*/
// 玩家信息数据库合约
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x410526CD583AF0bE0530166d53Efcd7da969F7B7);
/******************************************************************************************
社区地址
NT基金地址
代币空投的收款地址
*/
address public communityAddr_;
address public NTFoundationAddr_;
address private NTTokenSeller_ ;
/******************************************************************************************
设置代币地址
条件:
1. 地址不能为空
2. 管理员
*/
ERC20 private NTToken_ ;
function setNTToken(address addr) isAdmin() public {
require(address(addr) != address(0x0), "Empty address not allowed.");
NTToken_ = ERC20(addr);
}
/**
将游戏合约中的未用完的代币转走
条件:
1. 数值大于0
2. 管理员
*/
function transfer(address toAddr, uint256 amount) isAdmin() public returns (bool) {
require(amount > 0, "Must > 0 ");
NTToken_.transfer(toAddr, amount);
return true ;
}
/******************************************************************************************
启动
*/
bool public activated_ = false;
modifier isActivated() {
require(activated_ == true, "its not active yet.");
_;
}
/**
TODO
激活游戏
条件:
1、要是管理员
2、要设定代币地址
3、要设定用作奖池呼唤的游戏地址
4、只可以激活一次
*/
function activate() isAdmin() public {
// 必须设定代币地址
require(address(NTToken_) != address(0x0), "Must setup NTToken.");
// 必须设定社区基金地址
require(address(communityAddr_) != address(0x0), "Must setup CommunityAddr_.");
// 必须设定购买NT地址
require(address(NTTokenSeller_) != address(0x0), "Must setup NTTokenSeller.");
// 必须设定NT基金地址
require(address(NTFoundationAddr_) != address(0x0), "Must setup NTFoundationAddr.");
// 只能激活一次
require(activated_ == false, "Only once");
//
activated_ = true ;
// 初始化开始轮信息
rID_ = 1;
round_[1].strt = now ;
round_[1].end = now + rndMax_;
}
/******************************************************************************************
合约信息
*/
string constant public name = "NTech 3D Long Official"; // 合约名称
string constant public symbol = "NT3D"; // 合约符号
/**
*/
uint256 constant private rndInc_ = 1 minutes; // 每购买一个key延迟的时间
uint256 constant private rndMax_ = 6 hours; // 一轮的最长时间
uint256 private ntOf1Ether_ = 30000; // 一个以太兑换30000代币
/******************************************************************************************
奖池互换
*/
OtherNTech3D private otherNTech3D_ ; // 另外一个游戏接口,主要用作奖池呼唤
/**
设定奖池呼唤的另外一个游戏合约地址
条件
1. 管理员权限
2. 之前没有设定过
3. 设定的地址不能为空
*/
function setOtherNTech3D(address _otherNTech3D) isAdmin() public {
require(address(_otherNTech3D) != address(0x0), "Empty address not allowed.");
require(address(otherNTech3D_) == address(0x0), "OtherNTech3D has been set.");
otherNTech3D_ = OtherNTech3D(_otherNTech3D);
}
/******************************************************************************************
判断金额
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "Too little");
require(_eth <= 100000000000000000000000, "Too much");
_;
}
/******************************************************************************************
玩家信息
*/
// 玩家地址 => 玩家ID
mapping (address => uint256) public pIDxAddr_;
// 玩家名称 => 玩家ID
mapping (bytes32 => uint256) public pIDxName_;
// 玩家ID => 玩家信息
mapping (uint256 => NTech3DDatasets.Player) public plyr_;
// 玩家ID => 游戏轮编号 => 玩家游戏轮信息
mapping (uint256 => mapping (uint256 => NTech3DDatasets.PlayerRounds)) public plyrRnds_;
// 玩家ID => 玩家名称 =>
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
/******************************************************************************************
游戏信息
*/
uint256 public rID_; // 当前游戏轮编号
uint256 public airDropPot_; // 空投小奖池
uint256 public airDropTracker_ = 0; // 空投小奖池计数
// 游戏每轮ID => 游戏轮
mapping (uint256 => NTech3DDatasets.Round) public round_;
// 游戏每轮ID -> 团队ID => ETH
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_;
/******************************************************************************************
团队信息
0 : 水鲸队
1 : 懒熊队
2 : 玩蛇队
3 : 疯牛队
*/
// 团队ID => 分配规则
mapping (uint256 => NTech3DDatasets.TeamFee) public fees_;
// 团队ID => 分配规则
mapping (uint256 => NTech3DDatasets.PotSplit) public potSplit_;
/******************************************************************************************
构造函数
*/
constructor() public {
// 水鲸:本轮玩家 30% 空投 6%
fees_[0] = NTech3DDatasets.TeamFee(30,6);
// 懒熊:本轮玩家 43% 空投 0%
fees_[1] = NTech3DDatasets.TeamFee(43,0);
// 玩蛇:本轮玩家 56% 空投 10%
fees_[2] = NTech3DDatasets.TeamFee(56,10);
// 疯牛:本轮玩家 43% 空投 8%
fees_[3] = NTech3DDatasets.TeamFee(43,8);
// 此轮奖池分配:
// 水鲸:本轮玩家 25%
potSplit_[0] = NTech3DDatasets.PotSplit(15,10);
// 懒熊:本轮玩家 25%
potSplit_[1] = NTech3DDatasets.PotSplit(25,0);
// 玩蛇:本轮玩家 40%
potSplit_[2] = NTech3DDatasets.PotSplit(20,20);
// 疯牛:本轮玩家 40%
potSplit_[3] = NTech3DDatasets.PotSplit(30,10);
// 初始化用户管理
initUsers();
/**
*/
NTToken_ = ERC20(address(0x09341B5d43a9b2362141675b9276B777470222Be));
communityAddr_ = address(0x3C07f9f7164Bf72FDBefd9438658fAcD94Ed4439);
NTTokenSeller_ = address(0x531100a6b3686E6140f170B0920962A5D7A2DD25);
NTFoundationAddr_ = address(0x89b2E7Ee504afd522E07F80Ae7b9d4D228AF3fe2);
}
/******************************************************************************************
购买
*/
function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable {
NTech3DDatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID){
_affCode = plyr_[_pID].laff;
}else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
_team = verifyTeam(_team);
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable {
NTech3DDatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender){
_affID = plyr_[_pID].laff;
}else{
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff){
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable {
NTech3DDatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name){
_affID = plyr_[_pID].laff;
}else{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff){
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public {
NTech3DDatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID){
_affCode = plyr_[_pID].laff;
}else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public {
NTech3DDatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender){
_affID = plyr_[_pID].laff;
}else{
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff){
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public {
NTech3DDatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name){
_affID = plyr_[_pID].laff;
}else{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff){
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
撤退
*/
function withdraw() isActivated() isHuman() public {
uint256 _rID = rID_;
uint256 _now = now;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _eth;
if (_now > round_[_rID].end && (round_[_rID].ended == false) && round_[_rID].plyr != 0){
NTech3DDatasets.EventReturns memory _eventData_;
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit onWithdrawAndDistribute(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.NTAmount,
_eventData_.genAmount
);
}else{
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
emit onWithdraw(
_pID,
msg.sender,
plyr_[_pID].name,
_eth,
_now
);
}
}
/******************************************************************************************
注册
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit onNewName(
_pID,
_addr,
_name,
_isNewPlayer,
_affID,
plyr_[_affID].addr,
plyr_[_affID].name,
_paid,
now
);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit onNewName(
_pID,
_addr,
_name,
_isNewPlayer,
_affID,
plyr_[_affID].addr,
plyr_[_affID].name,
_paid,
now
);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit onNewName(
_pID,
_addr,
_name,
_isNewPlayer,
_affID,
plyr_[_affID].addr,
plyr_[_affID].name,
_paid,
now
);
}
/******************************************************************************************
获取购买价格
*/
function getBuyPrice() public view returns(uint256) {
uint256 _rID = rID_;
uint256 _now = now;
//if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/******************************************************************************************
得到剩余时间
*/
function getTimeLeft() public view returns(uint256) {
uint256 _rID = rID_;
uint256 _now = now;
if (_now < round_[_rID].end)
//if (_now > round_[_rID].strt + rndGap_)
if (_now > round_[_rID].strt)
return( (round_[_rID].end).sub(_now) );
else
//return( (round_[_rID].strt + rndGap_).sub(_now) );
return( (round_[_rID].end).sub(_now) );
else
return(0);
}
function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) {
uint256 _rID = rID_;
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0){
// if player is winner
if (round_[_rID].plyr == _pID){
// Added by Huwei
uint256 _pot = round_[_rID].pot.add(round_[_rID].prevres);
return
(
// Fix by huwei
//(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].win).add( ((_pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) {
// Fixed by Huwei
uint256 _pot = round_[_rID].pot.add(round_[_rID].prevres);
return( ((((round_[_rID].mask).add(((((_pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
//return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
得到当前此轮信息
*/
function getCurrentRoundInfo() public view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) {
uint256 _rID = rID_;
return
(
round_[_rID].ico,
_rID,
round_[_rID].keys,
round_[_rID].end,
round_[_rID].strt,
round_[_rID].pot,
(round_[_rID].team + (round_[_rID].plyr * 10)),
plyr_[round_[_rID].plyr].addr,
plyr_[round_[_rID].plyr].name,
rndTmEth_[_rID][0],
rndTmEth_[_rID][1],
rndTmEth_[_rID][2],
rndTmEth_[_rID][3],
airDropTracker_ + (airDropPot_ * 1000)
);
}
function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256){
uint256 _rID = rID_;
if (_addr == address(0)) {
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return (
_pID,
plyr_[_pID].name,
plyrRnds_[_pID][_rID].keys,
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff,
plyrRnds_[_pID][_rID].eth
);
}
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, NTech3DDatasets.EventReturns memory _eventData_) private {
uint256 _rID = rID_;
uint256 _now = now;
//if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) {
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) {
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
}else{
if (_now > round_[_rID].end && round_[_rID].ended == false) {
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit onBuyAndDistribute(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.NTAmount,
_eventData_.genAmount
);
}
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, NTech3DDatasets.EventReturns memory _eventData_) private {
uint256 _rID = rID_;
uint256 _now = now;
//if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) {
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) {
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
core(_rID, _pID, _eth, _affID, _team, _eventData_);
}else if (_now > round_[_rID].end && round_[_rID].ended == false) {
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit onReLoadAndDistribute(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.NTAmount,
_eventData_.genAmount
);
}
}
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, NTech3DDatasets.EventReturns memory _eventData_) private{
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// 每轮早期的限制 (5 ether 以下)
// 智能合约收到的总额达到100 ETH之前,每个以太坊地址最多只能购买总额10个ETH的Key。
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 10000000000000000000){
uint256 _availableLimit = (10000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
if (_eth > 1000000000) {
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
if (_keys >= 1000000000000000000){
updateTimer(_keys, _rID);
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
_eventData_.compressedData = _eventData_.compressedData + 100;
}
if (_eth >= 100000000000000000){
// > 0.1 ether, 才有空投
airDropTracker_++;
if (airdrop() == true){
uint256 _prize;
if (_eth >= 10000000000000000000){
// <= 10 ether
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
}else if(_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// >= 1 ether and < 10 ether
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 200000000000000000000000000000000;
}else if(_eth >= 100000000000000000 && _eth < 1000000000000000000){
// >= 0.1 ether and < 1 ether
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
}
_eventData_.compressedData += 10000000000000000000000000000000;
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
airDropTracker_ = 0;
}
}
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) {
// round_[_rIDlast].mask * plyrRnds_[_pID][_rIDlast].keys / 1000000000000000000 - plyrRnds_[_pID][_rIDlast].mask
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256){
uint256 _now = now;
//if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
function iWantXKeys(uint256 _keys) public view returns(uint256) {
uint256 _rID = rID_;
uint256 _now = now;
//if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
/**
interface : PlayerBookReceiverInterface
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external {
require (msg.sender == address(PlayerBook), "Called from PlayerBook only");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
function receivePlayerNameList(uint256 _pID, bytes32 _name) external {
require (msg.sender == address(PlayerBook), "Called from PlayerBook only");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
识别玩家
*/
function determinePID(NTech3DDatasets.EventReturns memory _eventData_) private returns (NTech3DDatasets.EventReturns) {
uint256 _pID = pIDxAddr_[msg.sender];
if (_pID == 0){
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != ""){
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return _eventData_ ;
}
/**
识别团队,默认是玩蛇队
*/
function verifyTeam(uint256 _team) private pure returns (uint256) {
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
function managePlayer(uint256 _pID, NTech3DDatasets.EventReturns memory _eventData_) private returns (NTech3DDatasets.EventReturns) {
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
plyr_[_pID].lrnd = rID_;
_eventData_.compressedData = _eventData_.compressedData + 10;
return _eventData_ ;
}
/**
这轮游戏结束
*/
function endRound(NTech3DDatasets.EventReturns memory _eventData_) private returns (NTech3DDatasets.EventReturns) {
uint256 _rID = rID_;
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
// Fixed by Huwei
//uint256 _pot = round_[_rID].pot;
uint256 _pot = round_[_rID].pot.add(round_[_rID].prevres);
// 赢家获取奖池的48%
uint256 _win = (_pot.mul(48)) / 100;
// 社区基金获取2%
uint256 _com = (_pot / 50);
// 这轮游戏玩家获取的奖金
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
// NT基金获取的奖金
uint256 _nt = (_pot.mul(potSplit_[_winTID].nt)) / 100;
// 剩下的奖金
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_nt);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0){
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
if(address(communityAddr_)!=address(0x0)) {
// 将社区基金奖金发到社区奖金地址
communityAddr_.transfer(_com);
_com = 0 ;
}else{
// 如果没有设置社区地址,那么资金分给下一轮
_res = SafeMath.add(_res,_com);
_com = 0 ;
}
if(_nt > 0) {
if(address(NTFoundationAddr_) != address(0x0)) {
// 分配NT基金奖金
NTFoundationAddr_.transfer(_nt);
}else{
// 如果没有设定,那么资金计入下一轮
_res = SafeMath.add(_res,_nt);
_nt = 0 ;
}
}
round_[_rID].mask = _ppt.add(round_[_rID].mask);
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.NTAmount = 0;
_eventData_.newPot = _res;
// 下一轮
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndMax_);
//round_[_rID].end = now.add(rndInit_).add(rndGap_);
// Fixed by Huwei
//round_[_rID].pot = _res;
round_[_rID].prevres = _res;
return(_eventData_);
}
function updateGenVault(uint256 _pID, uint256 _rIDlast) private {
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0){
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
function updateTimer(uint256 _keys, uint256 _rID) private {
uint256 _now = now;
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
计算空投小奖池
*/
function airdrop() private view returns(bool) {
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
/**
社区基金
奖池互换
分享
空投
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, NTech3DDatasets.EventReturns memory _eventData_)
private returns(NTech3DDatasets.EventReturns){
// 社区基金2%, 如果没有设置社区基金,则这份空投到用户地址
uint256 _com = _eth / 50;
// 奖池互换,如果没有设置,进入到社区基金
uint256 _long = _eth / 100;
if(address(otherNTech3D_)!=address(0x0)){
otherNTech3D_.potSwap.value(_long)();
}else{
_com = _com.add(_long);
}
// 分享,如果没有分享,进入到社区基金
uint256 _aff = _eth / 10;
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit onAffiliatePayout(
_affID,
plyr_[_affID].addr,
plyr_[_affID].name,
_rID,
_pID,
_aff,
now
);
} else {
_com = _com.add(_aff);
}
// 空投(如果没有设置社区基金地址,那么放入空投)
uint256 _nt = (_eth.mul(fees_[_team].nt)).div(100);
if(_com>0){
if(address(communityAddr_)!=address(0x0)) {
communityAddr_.transfer(_com);
}else{
_nt = _nt.add(_com);
}
}
if(_nt > 0 ){
// amount = _nt * ntOf1Ether_ ;
uint256 amount = _nt.mul(ntOf1Ether_);
_eventData_.NTAmount = amount.add(_eventData_.NTAmount);
NTToken_.transfer(msg.sender,amount);
//
address(NTTokenSeller_).transfer(_nt);
}
return (_eventData_) ;
}
/**
奖池互换
*/
function potSwap() external payable {
// 奖池互换放入下一轮
uint256 _rID = rID_ + 1;
// Fixed by Huwei
//round_[_rID].pot = round_[_rID].pot.add(msg.value);
round_[_rID].prevres = round_[_rID].prevres.add(msg.value);
emit onPotSwapDeposit(
_rID,
msg.value
);
}
/**
持有者
空投小奖池
终极奖池
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, NTech3DDatasets.EventReturns memory _eventData_)
private returns(NTech3DDatasets.EventReturns) {
// 持有者的份额
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// 空投小奖池 1%
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
// 14% = 2% 社区 + 10% 佣金 + 1% 奖池互换 + 1% 空投小奖池
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].nt)) / 100));
// 奖池
uint256 _pot = _eth.sub(_gen);
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) {
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
撤退时的收益
*/
function withdrawEarnings(uint256 _pID) private returns(uint256) {
updateGenVault(_pID, plyr_[_pID].lrnd);
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0){
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
完成交易
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, NTech3DDatasets.EventReturns memory _eventData_) private {
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit onEndTx(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.NTAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
} | ********************************************************** ERC20 interface/ | contract ERC20 {
function totalSupply() public view returns (uint supply);
function balanceOf( address who ) public view returns (uint value);
function allowance( address owner, address spender ) public view returns (uint _allowance);
function transfer( address to, uint value) public returns (bool ok);
function transferFrom( address from, address to, uint value) public returns (bool ok);
function approve( address spender, uint value ) public returns (bool ok);
event Transfer( address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
}
| 386,424 | [
1,
654,
39,
3462,
1560,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
4232,
39,
3462,
288,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
1135,
261,
11890,
14467,
1769,
203,
565,
445,
11013,
951,
12,
1758,
10354,
262,
1071,
1476,
1135,
261,
11890,
460,
1769,
203,
565,
445,
1699,
1359,
12,
1758,
3410,
16,
1758,
17571,
264,
262,
1071,
1476,
1135,
261,
11890,
389,
5965,
1359,
1769,
203,
203,
565,
445,
7412,
12,
1758,
358,
16,
2254,
460,
13,
1071,
1135,
261,
6430,
1529,
1769,
203,
565,
445,
7412,
1265,
12,
1758,
628,
16,
1758,
358,
16,
2254,
460,
13,
1071,
1135,
261,
6430,
1529,
1769,
203,
565,
445,
6617,
537,
12,
1758,
17571,
264,
16,
2254,
460,
262,
1071,
1135,
261,
6430,
1529,
1769,
203,
203,
565,
871,
12279,
12,
1758,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
460,
1769,
203,
565,
871,
1716,
685,
1125,
12,
1758,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
460,
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
]
|
pragma solidity ^0.4.23;
//
// Helper Contracts
//
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
* By OpenZeppelin. MIT License. https://github.com/OpenZeppelin/zeppelin-solidity
* This method has been modified by Glossy for two-step transfers since a mistake would be fatal.
*/
contract Ownable {
address public owner;
address public pendingOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
pendingOwner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Approve transfer as step one prior to transfer
* @param newOwner The address to transfer ownership to.
*/
function approveOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
pendingOwner = newOwner;
}
/**
* @dev Allows the pending owner to transfer control of the contract.
*/
function transferOwnership() public {
require(msg.sender == pendingOwner);
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
* By OpenZeppelin. MIT License. https://github.com/OpenZeppelin/zeppelin-solidity
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/** @title TXGuard
* @dev The purpose of this contract is to determine transfer fees to be sent to creators
**/
interface TXGuard {
function getTxAmount(uint256 _tokenId) external pure returns (uint256);
function getOwnerPercent(address _owner) external view returns (uint256);
}
/** @title ERC721MetadataExt
* @dev Metadata (externally) for the contract
**/
interface ERC721MetadataExt {
function getTokenURI(uint256 _tokenId) external pure returns (bytes32[4] buffer, uint16 count);
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId);
}
/** @title ERC721ERC721TokenReceiver
**/
interface ERC721TokenReceiver {
function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4);
}
/// @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) external view returns (uint256 balance);
function ownerOf(uint256 _tokenId) public view returns (address owner);
function approve(address _to, uint256 _tokenId) external payable;
function transfer(address _to, uint256 _tokenId) external payable;
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
// Events
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
// New Card is to ensure there is a record of card purchase in case an error occurs
event NewCard(address indexed _from, uint256 _cardId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event ContractUpgrade(address _newContract);
// Not in the standard, but using "Birth" to be consistent with announcing newly issued cards
event Birth(uint256 _newCardIndex, address _creator, string _metadata, uint256 _price, uint16 _max);
// 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 Glossy
* @dev This is the main Glossy contract
**/
contract Glossy is Pausable, ERC721 {
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
// From CryptoKitties. This is supported as well as the new 721 defs
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)'));
bytes4 private constant ERC721_RECEIVED = 0xf0b9e5ba;
/** @dev ERC165 implemented. This implements the original ERC721 interface
* as well as the "official" interface.
* @param _interfaceID the combined keccak256 hash of the interface methods
**/
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
return (_interfaceID == InterfaceSignature_ERC165 ||
_interfaceID == InterfaceSignature_ERC721 ||
_interfaceID == 0x80ac58cd ||
_interfaceID == 0x5b5e139f ||
_interfaceID == 0x780e9d63
);
}
uint256 public minimumPrice;
uint256 public globalCut;
address public pendingMaster;
address public masterAddress;
address public workerAddress;
string public metadataURL;
address public newContract;
address public txGuard;
address public erc721Metadata;
/* ERC20 Compatibility */
string public constant name = "Glossy";
string public constant symbol = "GLSY";
mapping (uint256 => address) public tokenIndexToOwner;
mapping (address => uint256) public ownershipTokenCount;
mapping (uint256 => address) public tokenIndexToApproved;
mapping (address => mapping (address => bool)) public operatorApprovals;
modifier canOperate(uint256 _tokenId) {
address owner = tokenIndexToOwner[_tokenId];
require(msg.sender == owner || operatorApprovals[owner][msg.sender]);
_;
}
modifier canTransfer(uint256 _tokenId) {
address owner = tokenIndexToOwner[_tokenId];
require(msg.sender == owner ||
msg.sender == tokenIndexToApproved[_tokenId] ||
operatorApprovals[owner][msg.sender]);
_;
}
modifier onlyMaster() {
require(msg.sender == masterAddress);
_;
}
modifier onlyWorker() {
require(msg.sender == workerAddress);
_;
}
//
// Setting addresses for control and contract helpers
//
/** @dev Set the master address responsible for function level contract control
* @param _newMaster New Address for master
**/
function setMaster(address _newMaster) external onlyMaster {
require(_newMaster != address(0));
pendingMaster = _newMaster;
}
/** @dev Accept master address
**/
function acceptMaster() external {
require(pendingMaster != address(0));
require(pendingMaster == msg.sender);
masterAddress = pendingMaster;
}
/** @dev Set the worker address responsible for card creation
* @param _newWorker New Worker for card creation
**/
function setWorker(address _newWorker) external onlyMaster {
require(_newWorker != address(0));
workerAddress = _newWorker;
}
/** @dev Set new contract address, emits a ContractUpgrade
* @param _newContract The address of the new contract
**/
function setContract(address _newContract) external onlyOwner {
require(_newContract != address(0));
emit ContractUpgrade(_newContract);
newContract = _newContract;
}
/** @dev Set contract for txGuard, a contract used to recover funds on transfers
* @param _txGuard address for txGuard
**/
function setTxGuard(address _txGuard) external onlyMaster {
require(_txGuard != address(0));
txGuard = _txGuard;
}
/** @dev Set ERC721Metadata contract
* @param _erc721Metadata is the contract address
**/
function setErc721Metadata(address _erc721Metadata) external onlyMaster {
require(_erc721Metadata != address(0));
erc721Metadata = _erc721Metadata;
}
/* This structure attempts to minimize data stored in contract.
On average, assuming 10 cards, it would use 128 bits which is
reasonable in terms of storage. CK uses 512 bits per token.
Baseline 512 bits
Single 1024 bits
Average (1024 + 256) / 10 = 128 bits
*/
struct Card {
uint16 count; // 16
uint16 max; // 16
uint256 price; // 256
address creator; // 160
string dataHash; // 256
string metadata; // 320
}
// Structure done this way for readability
struct Token {
uint256 card;
}
Card[] cards;
Token[] tokens;
constructor(address _workerAddress, uint256 _minimumPrice, uint256 _globalCut, string _metadataURL) public {
masterAddress = msg.sender;
workerAddress = _workerAddress;
minimumPrice = _minimumPrice;
globalCut = _globalCut;
metadataURL = _metadataURL;
// Create a card 0, necessary as a placeholder for new card creation
_newCard(0,0,0,address(0),"","");
}
//
// Enumerated
//
/** @dev Total supply of Glossy cards
**/
function totalSupply() public view returns (uint256 _totalTokens) {
return tokens.length;
}
/** @dev A token identifier for the given index
* @param _index the index of the token
**/
function tokenByIndex(uint256 _index) external pure returns (uint256) {
return _index + 1;
}
//
//
//
/** @dev Balance for a particular address.
* @param _owner The owner of the returned balance
**/
function balanceOf(address _owner) external view returns (uint256 _balance) {
return ownershipTokenCount[_owner];
}
/**** ERC721 ****/
function _newCard(uint16 _count, uint16 _max, uint256 _price, address _creator, string _dataHash, string _metadata) internal returns (uint256 newCardIndex){
Card memory card = Card({
count:_count,
max:_max,
price:_price,
creator:_creator,
dataHash:_dataHash,
metadata:_metadata
});
newCardIndex = cards.push(card) - 1;
emit Birth(newCardIndex, _creator, _metadata, _price, _max);
}
// Worker will populate a card and assign it to the token
function populateNew(uint16 _max, uint256 _price, address _creator, string _dataHash, string _metadata, uint256 _tokenId) external onlyWorker {
uint16 count = (_tokenId == 0 ? 0 : 1);
uint256 newCardIndex = _newCard(count, _max, _price, _creator, _dataHash, _metadata);
// If we are creating a new series entirely programmatically
if(_tokenId == 0) {
return;
}
// Make sure the token at the index isn't already populated.
require(tokens[_tokenId].card == 0);
// Set the card to the newly added card index
tokens[_tokenId].card = newCardIndex;
// We have to transfer at this point rather than purchaseNew
uint256 cutAmount = _getCut(uint128(_price), _creator);
uint256 amount = _price - cutAmount;
_creator.transfer(amount);
}
// Hopefully never needed.
function correctNew(uint256 _cardId, uint256 _tokenId) external onlyWorker {
// Make sure the token at the index isn't already populated.
require(tokens[_tokenId].card == 0);
// Set the card to the newly added card index
tokens[_tokenId].card = _cardId;
}
// Purchase hot off the press
// Accept funds and let backend authorize the rest
function purchaseNew(uint256 _cardId) external payable whenNotPaused returns (uint256 tokenId) {
// Must be minimum purchase price to prevent empty tokens being bought for ~0
require(msg.value >= minimumPrice);
//
// Transfer the token, step 1 of a two step process.
tokenId = tokens.push(Token({card:0})) - 1;
tokenIndexToOwner[tokenId] = msg.sender;
ownershipTokenCount[msg.sender]++;
emit NewCard(msg.sender, _cardId);
emit Transfer(address(0), msg.sender, tokenId);
}
// Standard purchase, website is responsible for calling this OR purchaseNew
function purchase(uint256 _cardId) public payable whenNotPaused {
Card storage card = cards[_cardId];
address creator = card.creator;
require(card.count < card.max);
require(msg.value == card.price);
card.count++;
uint256 tokenId = tokens.push(Token({card:_cardId})) - 1;
tokenIndexToOwner[tokenId] = msg.sender;
ownershipTokenCount[msg.sender]++;
emit Transfer(address(0), msg.sender, tokenId);
uint256 amount = msg.value - _getCut(uint128(msg.value), creator);
creator.transfer(amount);
}
/* Internal transfer method */
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Update ownership counts
ownershipTokenCount[_from]--;
ownershipTokenCount[_to]++;
// Transfer ownership
tokenIndexToOwner[_tokenId] = _to;
// Emit transfer event
emit Transfer(_from, _to, _tokenId);
}
/** @dev Transfer asset to a particular address.
* @param _to Address receiving the asset
* @param _tokenId ID of asset
**/
function transfer(address _to, uint256 _tokenId) external payable whenNotPaused {
require(_to != address(0));
require(_to != address(this));
require(msg.sender == ownerOf(_tokenId));
// txGuard is a mechanism that allows a percentage of the transaction to be accepted to benefit asset holders
if(txGuard != address(0)) {
require(TXGuard(txGuard).getTxAmount(_tokenId) == msg.value);
transferCut(msg.value, _tokenId);
}
_transfer(msg.sender, _to, _tokenId);
}
/** @dev Transfer asset to a particular address by worker
* @param _to Address receiving the asset
* @param _tokenId ID of asset
**/
function transferByWorker(address _to, uint256 _tokenId) external onlyWorker {
require(_to != address(0));
require(_to != address(this));
_transfer(msg.sender, _to, _tokenId);
}
/* Two step transfer to ensure ownership */
function approve(address _approved, uint256 _tokenId) external payable canOperate(_tokenId) {
address _owner = tokenIndexToOwner[_tokenId];
if (_owner == address(0)) {
_owner = address(this);
}
tokenIndexToApproved[_tokenId] = _approved;
emit Approval(_owner, _approved, _tokenId);
}
function setApprovalForAll(address _operator, bool _approved) external {
operatorApprovals[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
function getApproved(uint256 _tokenId) external view returns (address) {
return tokenIndexToApproved[_tokenId];
}
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
return operatorApprovals[_owner][_operator];
}
function transferFrom(address _from, address _to, uint256 _tokenId) payable whenNotPaused external {
require(_to != address(0));
require(_to != address(this));
require(tokenIndexToApproved[_tokenId] == msg.sender);
require(_from == ownerOf(_tokenId));
// txGuard is a mechanism that allows a percentage of the transaction to be accepted to benefit asset holders
if(txGuard != address(0)) {
require(TXGuard(txGuard).getTxAmount(_tokenId) == msg.value);
transferCut(msg.value, _tokenId);
}
_transfer(_from, _to, _tokenId);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable whenNotPaused {
_safeTransferFrom(_from, _to, _tokenId, data);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable whenNotPaused {
_safeTransferFrom(_from, _to, _tokenId, "");
}
function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) private canTransfer(_tokenId) {
address owner = tokenIndexToOwner[_tokenId];
if (owner == address(0)) {
owner = address(this);
}
require(owner == _from);
require(_to != address(0));
if(txGuard != address(0)) {
require(TXGuard(txGuard).getTxAmount(_tokenId) == msg.value);
transferCut(msg.value, _tokenId);
}
_transfer(_from, _to, _tokenId);
uint256 codeSize;
assembly { codeSize := extcodesize(_to) }
if(codeSize == 0) {
return;
}
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, data);
require(retval == ERC721_RECEIVED);
}
/** @dev Take a token and attempt to transfer copies to multiple addresses.
* This can only be executed by a worker.
* @param _to Addresses receiving the asset.
* @param _cardId The card for which tokens should be assigned
**/
function multiTransfer(address[] _to, uint256 _cardId) external onlyWorker {
Card storage _card = cards[_cardId];
require(_card.count + _to.length <= _card.max);
_card.count = _card.count + uint8(_to.length);
for(uint16 i = 0; i < _to.length; i++) {
uint256 tokenId = tokens.push(Token({card:_cardId})) - 1;
address newOwner = _to[i];
tokenIndexToOwner[tokenId] = newOwner;
ownershipTokenCount[newOwner]++;
emit Transfer(address(0), newOwner, tokenId);
}
}
/** @dev Returns the owner of the token index given.
* @param _tokenId The token index whose owner is queried.
**/
function ownerOf(uint256 _tokenId) public view returns (address owner) {
owner = tokenIndexToOwner[_tokenId];
}
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId) {
require(erc721Metadata != address(0));
_tokenId = ERC721MetadataExt(erc721Metadata).tokenOfOwnerByIndex(_owner, _index);
}
function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds) {
require(erc721Metadata != address(0));
uint256 bal = this.balanceOf(_owner);
uint256[] memory _tokenIds = new uint256[](bal);
uint256 _index = 0;
for(; _index < bal; _index++) {
_tokenIds[_index] = this.tokenOfOwnerByIndex(_owner, _index);
}
return _tokenIds;
}
/** @dev This returns the metadata for the given token.
* tokenURI points to another contract, by default at address 0.
* Metadata is still being debated, and the current implementation requires
* some verbose JSON which seems against the spirit of data efficiency. The
* ERC721 tokenMetadata method is implemented for compatibility.
* @param _tokenId The token index for which the metadata should be returned.
**/
function tokenURI(uint256 _tokenId) external view returns (string infoUrl) {
require(erc721Metadata != address(0));
// URL for metadata
bytes32[4] memory buffer;
uint256 count;
(buffer, count) = ERC721MetadataExt(erc721Metadata).getTokenURI(_tokenId);
return _toString(buffer, count);
}
/** @dev This returns the metadata for the given token.
* This is currently supported while tokenURI is not.
* @param _tokenId The token index for which the metadata should be returned.
* @param _preferredTransport The protocol (https, ipfs) of the metadata source.
**/
function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string metadata) {
Token storage _token = tokens[_tokenId];
Card storage _card = cards[_token.card];
if(keccak256(_preferredTransport) == keccak256("http")) {
return _concat(metadataURL, _card.metadata);
}
return _card.metadata;
}
/** @dev Set the metadata URL
* @param _metadataURL New URL
**/
function setMetadataURL(string _metadataURL) external onlyMaster {
metadataURL = _metadataURL;
}
function setMinimumPrice(uint256 _minimumPrice) external onlyMaster {
minimumPrice = _minimumPrice;
}
function setCreatorAddress(address _newAddress, uint256 _cardId) external whenNotPaused {
Card storage card = cards[_cardId];
address creator = card.creator;
require(_newAddress != address(0));
require(msg.sender == creator);
card.creator = _newAddress;
}
/** @dev This is a withdrawl method, though it isn't intended to be used often or for much.
* @param _amount Amount to be moved
**/
function withdrawAmount(uint256 _amount) external onlyMaster {
uint256 balance = address(this).balance;
require(_amount <= balance);
masterAddress.transfer(_amount);
}
/** @dev This returns the amount required to send the contract for a transfer.
* @param _tokenId The token index to be checked
**/
function getTxAmount(uint256 _tokenId) external view returns (uint256 _amount) {
if(txGuard == address(0))
return 0;
return TXGuard(txGuard).getTxAmount(_tokenId);
}
/** @dev Transfer a fixed cut to the asset owner
* @param _cutAmount amount of cut
**/
function transferCut(uint256 _cutAmount, uint256 _tokenId) internal {
Token storage _token = tokens[_tokenId];
Card storage _card = cards[_token.card];
address creatorAddress = _card.creator;
uint256 creatorAmount = _cutAmount - _getCut(uint128(_cutAmount * 15), creatorAddress);
creatorAddress.transfer(creatorAmount);
}
/** @dev Set the global cut
* @param _cut percentage of asset transaction
**/
function setGlobalCut(uint256 _cut) external onlyMaster {
globalCut = _cut;
}
/** @dev Get the cut for contract operations
* @param _amount Total price of item
**/
function _getCut(uint128 _amount, address _creator) internal view returns (uint256) {
if(txGuard != address(0)) {
return _amount * TXGuard(txGuard).getOwnerPercent(_creator) / 10000;
}
return _amount * globalCut / 10000;
}
// Helper Functions
/** @dev Via CryptoKitties: 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 pure {
// 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 Via CryptoKitties: 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) internal pure returns (string outputString) {
outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
}
/** @dev This method takes two strings, concatenates the bytes, and then returns a string.
* @param _first First string
* @param _second Second string
**/
function _concat(string _first, string _second) internal pure returns (string _result){
bytes memory __first = bytes(_first);
bytes memory __second = bytes(_second);
_result = new string(__first.length + __second.length);
bytes memory __result = bytes(_result);
uint ptr = 0;
uint i = 0;
for (; i < __first.length; i++)
__result[ptr++] = __first[i];
for (i = 0; i < __second.length; i++)
__result[ptr++] = __second[i];
_result = string(__result);
}
}
| * @dev Total supply of Glossy cards/ | function totalSupply() public view returns (uint256 _totalTokens) {
return tokens.length;
}
| 14,017,887 | [
1,
5269,
14467,
434,
611,
7873,
93,
18122,
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,
225,
445,
2078,
3088,
1283,
1435,
1071,
1476,
1135,
261,
11890,
5034,
389,
4963,
5157,
13,
288,
203,
565,
327,
2430,
18,
2469,
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
]
|
pragma solidity 0.4.18;
import '../core/RequestCore.sol';
import '../base/math/SafeMath.sol';
import '../base/lifecycle/Pausable.sol';
/**
* @title RequestEthereum
*
* @dev RequestEthereum is the currency contract managing the request payed in Ethereum
*
* @dev Requests can be created by the Payee with createRequest() or by the payer from a request signed offchain by the payee with createQuickRequest
* @dev Requests don't have extension for now
*/
contract RequestEthereum is Pausable {
using SafeMath for uint256;
// RequestCore object
RequestCore public requestCore;
// Ethereum available to withdraw
mapping(address => uint256) public ethToWithdraw;
/*
* Events
*/
event EtherAvailableToWithdraw(bytes32 indexed requestId, address recipient, uint256 amount);
/*
* @dev Constructor
* @param _requestCoreAddress Request Core address
*/
function RequestEthereum(address _requestCoreAddress) public
{
requestCore=RequestCore(_requestCoreAddress);
}
/*
* @dev Function to create a request as payee
*
* @dev msg.sender will be the payee
*
* @param _payer Entity supposed to pay
* @param _expectedAmount Expected amount to be received.
* @param _extension NOT USED (will be use later)
* @param _extensionParams NOT USED (will be use later)
* @param _data Hash linking to additional data on the Request stored on IPFS
*
* @return Returns the id of the request
*/
function createRequestAsPayee(address _payer, int256 _expectedAmount, address _extension, bytes32[9] _extensionParams, string _data)
external
payable
whenNotPaused
returns(bytes32 requestId)
{
require(_expectedAmount>=0);
require(msg.sender != _payer && _payer != 0);
requestId= requestCore.createRequest.value(msg.value)(msg.sender, msg.sender, _payer, _expectedAmount, 0, _data);
return requestId;
}
/*
* @dev Function to create a request as payer
*
* @dev msg.sender will be the payer
*
* @param _payee Entity which will receive the payment
* @param _expectedAmount Expected amount to be received
* @param _extension NOT USED (will be use later)
* @param _extensionParams NOT USED (will be use later)
* @param _additionals Will increase the ExpectedAmount of the request right after its creation by adding additionals
* @param _data Hash linking to additional data on the Request stored on IPFS
*
* @return Returns the id of the request
*/
function createRequestAsPayer(address _payee, int256 _expectedAmount, address _extension, bytes32[9] _extensionParams, uint256 _additionals, string _data)
external
payable
whenNotPaused
returns(bytes32 requestId)
{
return createAcceptAndPay(msg.sender, _payee, _expectedAmount, _extension, _extensionParams, _additionals, _data);
}
/*
* @dev Function to broadcast and accept an offchain signed request (can be paid and additionals also)
*
* @dev msg.sender must be _payer
* @dev the _payer can additionals
*
* @param _payee Entity which will receive the payment
* @param _payer Entity supposed to pay
* @param _expectedAmount Expected amount to be received. This amount can't be changed.
* @param _extension an extension can be linked to a request and allows advanced payments conditions such as escrow. Extensions have to be whitelisted in Core NOT USED (will be use later)
* @param _extensionParams Parameters for the extension. It is an array of 9 bytes32 NOT USED (will be use later)
* @param _additionals amount of additionals the payer want to declare
* @param v ECDSA signature parameter v.
* @param r ECDSA signature parameters r.
* @param s ECDSA signature parameters s.
*
* @return Returns the id of the request
*/
function broadcastSignedRequestAsPayer(address _payee, int256 _expectedAmount, address _extension, bytes32[9] _extensionParams, uint256 _additionals, string _data, uint256 _expirationDate, uint8 v, bytes32 r, bytes32 s)
external
payable
whenNotPaused
returns(bytes32)
{
// check expiration date
require(_expirationDate >= block.timestamp);
// check the signature
require(checkRequestSignature(_payee, _payee, 0, _expectedAmount,_extension,_extensionParams, _data, _expirationDate, v, r, s));
return createAcceptAndPay(_payee, _payee, _expectedAmount, _extension, _extensionParams, _additionals, _data);
}
/*
* @dev Internal function to create,accept and pay a request as Payer
*
* @dev msg.sender will be the payer
*
* @param _creator Entity which create the request
* @param _payee Entity which will receive the payment
* @param _expectedAmount Expected amount to be received
* @param _extension NOT USED (will be use later)
* @param _extensionParams NOT USED (will be use later)
* @param _additionals Will increase the ExpectedAmount of the request right after its creation by adding additionals
* @param _data Hash linking to additional data on the Request stored on IPFS
*
* @return Returns the id of the request
*/
function createAcceptAndPay(address _creator, address _payee, int256 _expectedAmount, address _extension, bytes32[9] _extensionParams, uint256 _additionals, string _data)
internal
returns(bytes32 requestId)
{
require(_expectedAmount>=0);
require(msg.sender != _payee && _payee != 0);
uint256 collectAmount = requestCore.getCollectEstimation(_expectedAmount, this, _extension);
requestId = requestCore.createRequest.value(collectAmount)(_creator, _payee, msg.sender, _expectedAmount, _extension, _data);
requestCore.accept(requestId);
if(_additionals > 0) {
requestCore.updateExpectedAmount(requestId, _additionals.toInt256Safe());
}
if(msg.value-collectAmount > 0) {
paymentInternal(requestId, msg.value-collectAmount);
}
return requestId;
}
// ---- INTERFACE FUNCTIONS ------------------------------------------------------------------------------------
/*
* @dev Function to accept a request
*
* @dev msg.sender must be _payer
* @dev A request can also be accepted by using directly the payment function on a request in the Created status
*
* @param _requestId id of the request
*
* @return true if the request is accepted, false otherwise
*/
function accept(bytes32 _requestId)
external
whenNotPaused
condition(requestCore.getPayer(_requestId)==msg.sender && requestCore.getState(_requestId)==RequestCore.State.Created)
{
requestCore.accept(_requestId);
}
/*
* @dev Function to cancel a request
*
* @dev msg.sender must be the _payer or the _payee.
* @dev only request with balance equals to zero can be cancel
*
* @param _requestId id of the request
*
* @return true if the request is canceled
*/
function cancel(bytes32 _requestId)
external
whenNotPaused
{
require((requestCore.getPayer(_requestId)==msg.sender && requestCore.getState(_requestId)==RequestCore.State.Created)
|| (requestCore.getPayee(_requestId)==msg.sender && requestCore.getState(_requestId)!=RequestCore.State.Canceled));
// impossible to cancel a Request with a balance != 0
require(requestCore.getBalance(_requestId) == 0);
requestCore.cancel(_requestId);
}
// ----------------------------------------------------------------------------------------
// ---- CONTRACT FUNCTIONS ------------------------------------------------------------------------------------
/*
* @dev Function PAYABLE to pay in ether a request
*
* @dev the request must be accepted if msg.sender!=payer
* @dev the request will be automatically accepted if msg.sender==payer
*
* @param _requestId id of the request
* @param _additionals amount of additionals in wei to declare
*/
function paymentAction(bytes32 _requestId, uint256 _additionals)
external
whenNotPaused
payable
condition(requestCore.getState(_requestId)==RequestCore.State.Accepted || (requestCore.getState(_requestId)==RequestCore.State.Created && requestCore.getPayer(_requestId)==msg.sender))
condition(_additionals==0 || requestCore.getPayer(_requestId)==msg.sender)
{
// automatically accept request
if(requestCore.getState(_requestId)==RequestCore.State.Created) {
requestCore.accept(_requestId);
}
if(_additionals > 0) {
requestCore.updateExpectedAmount(_requestId, _additionals.toInt256Safe());
}
paymentInternal(_requestId, msg.value);
}
/*
* @dev Function PAYABLE to pay back in ether a request to the payee
*
* @dev msg.sender must be _payer
* @dev the request must be accepted
* @dev the payback must be lower than the amount already paid for the request
*
* @param _requestId id of the request
*/
function refundAction(bytes32 _requestId)
external
whenNotPaused
condition(requestCore.getState(_requestId)==RequestCore.State.Accepted)
onlyRequestPayee(_requestId)
payable
{
refundInternal(_requestId, msg.value);
}
/*
* @dev Function to declare a subtract
*
* @dev msg.sender must be _payee
* @dev the request must be accepted or created
*
* @param _requestId id of the request
* @param _amount amount of subtract in wei to declare
*/
function subtractAction(bytes32 _requestId, uint256 _amount)
external
whenNotPaused
condition(requestCore.getState(_requestId)==RequestCore.State.Accepted || requestCore.getState(_requestId)==RequestCore.State.Created)
// subtract must be equal or lower than amount expected
condition(requestCore.getExpectedAmount(_requestId) >= _amount.toInt256Safe())
onlyRequestPayee(_requestId)
{
requestCore.updateExpectedAmount(_requestId, -_amount.toInt256Safe());
}
/*
* @dev Function to declare an additional
*
* @dev msg.sender must be _payer
* @dev the request must be accepted or created
*
* @param _requestId id of the request
* @param _amount amount of additional in wei to declare
*/
function additionalAction(bytes32 _requestId, uint256 _amount)
external
whenNotPaused
condition(requestCore.getState(_requestId)==RequestCore.State.Accepted || requestCore.getState(_requestId)==RequestCore.State.Created)
onlyRequestPayer(_requestId)
{
requestCore.updateExpectedAmount(_requestId, _amount.toInt256Safe());
}
/*
* @dev Function to withdraw ether
*/
function withdraw()
public
{
uint256 amount = ethToWithdraw[msg.sender];
ethToWithdraw[msg.sender] = 0;
msg.sender.transfer(amount);
}
// ----------------------------------------------------------------------------------------
// ---- INTERNAL FUNCTIONS ------------------------------------------------------------------------------------
/*
* @dev Function internal to manage payment declaration
*
* @param _requestId id of the request
* @param _amount amount of payment in wei to declare
*
* @return true if the payment is done, false otherwise
*/
function paymentInternal(bytes32 _requestId, uint256 _amount)
internal
{
requestCore.updateBalance(_requestId, _amount.toInt256Safe());
// payment done, the money is ready to withdraw by the payee
fundOrderInternal(_requestId, requestCore.getPayee(_requestId), _amount);
}
/*
* @dev Function internal to manage refund declaration
*
* @param _requestId id of the request
* @param _amount amount of the refund in wei to declare
*
* @return true if the refund is done, false otherwise
*/
function refundInternal(bytes32 _requestId, uint256 _amount)
internal
{
requestCore.updateBalance(_requestId, -_amount.toInt256Safe());
// payment done, the money is ready to withdraw by the payee
fundOrderInternal(_requestId, requestCore.getPayer(_requestId), _amount);
}
/*
* @dev Function internal to manage fund mouvement
*
* @param _requestId id of the request
* @param _recipient adress where the wei has to me send to
* @param _amount amount in wei to send
*
* @return true if the fund mouvement is done, false otherwise
*/
function fundOrderInternal(bytes32 _requestId, address _recipient, uint256 _amount)
internal
{
// try to send the fund
if(!_recipient.send(_amount)) {
// if sendding fail, the funds are availbale to withdraw
ethToWithdraw[_recipient] = ethToWithdraw[_recipient].add(_amount);
// spread the word that the money is not sent but available to withdraw
EtherAvailableToWithdraw(_requestId, _recipient, _amount);
}
}
/*
* @dev Function internal to calculate Keccak-256 hash of a request with specified parameters
*
* @param _payee Entity which will receive the payment.
* @param _payer Entity supposed to pay.
* @param _expectedAmount Expected amount to be received. This amount can't be changed.
* @param _extension extension of the request.
* @param _extensionParams Parameters for the extension.
*
* @return Keccak-256 hash of a request
*/
function getRequestHash(address _payee, address _payer, int256 _expectedAmount, address _extension, bytes32[9] _extensionParams, string _data, uint256 _expirationDate)
internal
view
returns(bytes32)
{
return keccak256(this,_payee,_payer,_expectedAmount,_extension,_extensionParams,_data,_expirationDate);
}
/*
* @dev Verifies that a hash signature is valid. 0x style
* @param signer address of signer.
* @param hash Signed Keccak-256 hash.
* @param v ECDSA signature parameter v.
* @param r ECDSA signature parameters r.
* @param s ECDSA signature parameters s.
* @return Validity of order signature.
*/
function isValidSignature(
address signer,
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s)
public
pure
returns (bool)
{
return signer == ecrecover(
keccak256("\x19Ethereum Signed Message:\n32", hash),
v,
r,
s
);
}
function checkRequestSignature(
address signer,
address payee,
address payer,
int256 expectedAmount,
address extension,
bytes32[9] extensionParams,
string data,
uint256 expirationDate,
uint8 v,
bytes32 r,
bytes32 s)
public
view
returns (bool)
{
bytes32 hash = getRequestHash(payee,payer,expectedAmount,extension,extensionParams,data,expirationDate);
return isValidSignature(signer, hash, v, r, s);
}
//modifier
modifier condition(bool c)
{
require(c);
_;
}
/*
* @dev Modifier to check if msg.sender is payer
* @dev Revert if msg.sender is not payer
* @param _requestId id of the request
*/
modifier onlyRequestPayer(bytes32 _requestId)
{
require(requestCore.getPayer(_requestId)==msg.sender);
_;
}
/*
* @dev Modifier to check if msg.sender is payee
* @dev Revert if msg.sender is not payee
* @param _requestId id of the request
*/
modifier onlyRequestPayee(bytes32 _requestId)
{
require(requestCore.getPayee(_requestId)==msg.sender);
_;
}
/*
* @dev Modifier to check if msg.sender is payee or payer
* @dev Revert if msg.sender is not payee or payer
* @param _requestId id of the request
*/
modifier onlyRequestPayeeOrPayer(bytes32 _requestId)
{
require(requestCore.getPayee(_requestId)==msg.sender || requestCore.getPayer(_requestId)==msg.sender);
_;
}
/*
* @dev Modifier to check if request is in a specify state
* @dev Revert if request not in a specify state
* @param _requestId id of the request
* @param _state state to check
*/
modifier onlyRequestState(bytes32 _requestId, RequestCore.State _state)
{
require(requestCore.getState(_requestId)==_state);
_;
}
}
| @dev Function internal to calculate Keccak-256 hash of a request with specified parameters @param _payee Entity which will receive the payment. @param _payer Entity supposed to pay. @param _expectedAmount Expected amount to be received. This amount can't be changed. @param _extension extension of the request. @param _extensionParams Parameters for the extension. @return Keccak-256 hash of a request/ | function getRequestHash(address _payee, address _payer, int256 _expectedAmount, address _extension, bytes32[9] _extensionParams, string _data, uint256 _expirationDate)
internal
view
returns(bytes32)
{
return keccak256(this,_payee,_payer,_expectedAmount,_extension,_extensionParams,_data,_expirationDate);
}
| 12,971,446 | [
1,
2083,
2713,
358,
4604,
1475,
24410,
581,
17,
5034,
1651,
434,
279,
590,
598,
1269,
1472,
225,
389,
10239,
1340,
3887,
1492,
903,
6798,
326,
5184,
18,
225,
389,
84,
1773,
3887,
18405,
358,
8843,
18,
225,
389,
3825,
6275,
13219,
3844,
358,
506,
5079,
18,
1220,
3844,
848,
1404,
506,
3550,
18,
225,
389,
6447,
2710,
434,
326,
590,
18,
225,
389,
6447,
1370,
7012,
364,
326,
2710,
18,
327,
1475,
24410,
581,
17,
5034,
1651,
434,
279,
590,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
915,
4328,
2310,
12,
2867,
389,
10239,
1340,
16,
1758,
389,
84,
1773,
16,
509,
5034,
389,
3825,
6275,
16,
1758,
389,
6447,
16,
1731,
1578,
63,
29,
65,
389,
6447,
1370,
16,
533,
389,
892,
16,
2254,
5034,
389,
19519,
1626,
13,
203,
202,
202,
7236,
203,
202,
202,
1945,
203,
202,
202,
6154,
12,
3890,
1578,
13,
203,
202,
95,
203,
202,
202,
2463,
417,
24410,
581,
5034,
12,
2211,
16,
67,
10239,
1340,
16,
67,
84,
1773,
16,
67,
3825,
6275,
16,
67,
6447,
16,
67,
6447,
1370,
16,
67,
892,
16,
67,
19519,
1626,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xe6A58bd320dc339E51C4f832318073b596E1637a/sources/OpenSwap.sol | @dev batch set quota for early user quota if openTag <=0, removed | function addWhiteList(uint8 stage, address user, bool openTag)
external
onlyOwner
{
_fullWhiteList[stage][user] = openTag;
}
| 4,245,989 | [
1,
5303,
444,
13257,
364,
11646,
729,
13257,
309,
28059,
1648,
20,
16,
3723,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
13407,
682,
12,
11890,
28,
6009,
16,
1758,
729,
16,
1426,
28059,
13,
203,
3639,
3903,
203,
3639,
1338,
5541,
203,
565,
288,
203,
3639,
389,
2854,
13407,
682,
63,
12869,
6362,
1355,
65,
273,
28059,
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
]
|
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "./interfaces/INodeOperatorRegistry.sol";
import "./interfaces/IValidatorFactory.sol";
import "./interfaces/IValidator.sol";
import "./interfaces/IStMATIC.sol";
/// @title NodeOperatorRegistry
/// @author 2021 ShardLabs.
/// @notice NodeOperatorRegistry is the main contract that manage validators
/// @dev NodeOperatorRegistry is the main contract that manage operators.
contract NodeOperatorRegistry is
INodeOperatorRegistry,
PausableUpgradeable,
AccessControlUpgradeable,
ReentrancyGuardUpgradeable
{
enum NodeOperatorStatus {
INACTIVE,
ACTIVE,
STOPPED,
UNSTAKED,
CLAIMED,
EXIT,
JAILED,
EJECTED
}
/// @notice The node operator struct
/// @param status node operator status(INACTIVE, ACTIVE, STOPPED, CLAIMED, UNSTAKED, EXIT, JAILED, EJECTED).
/// @param name node operator name.
/// @param rewardAddress Validator public key used for access control and receive rewards.
/// @param validatorId validator id of this node operator on the polygon stake manager.
/// @param signerPubkey public key used on heimdall.
/// @param validatorShare validator share contract used to delegate for on polygon.
/// @param validatorProxy the validator proxy, the owner of the validator.
/// @param commissionRate the commission rate applied by the operator on polygon.
/// @param maxDelegateLimit max delegation limit that StMatic contract will delegate to this operator each time delegate function is called.
struct NodeOperator {
NodeOperatorStatus status;
string name;
address rewardAddress;
bytes signerPubkey;
address validatorShare;
address validatorProxy;
uint256 validatorId;
uint256 commissionRate;
uint256 maxDelegateLimit;
}
/// @notice all the roles.
bytes32 public constant REMOVE_OPERATOR_ROLE =
keccak256("LIDO_REMOVE_OPERATOR");
bytes32 public constant PAUSE_OPERATOR_ROLE =
keccak256("LIDO_PAUSE_OPERATOR");
bytes32 public constant DAO_ROLE = keccak256("LIDO_DAO");
/// @notice contract version.
string public version;
/// @notice total node operators.
uint256 private totalNodeOperators;
/// @notice validatorFactory address.
address private validatorFactory;
/// @notice stakeManager address.
address private stakeManager;
/// @notice polygonERC20 token (Matic) address.
address private polygonERC20;
/// @notice stMATIC address.
address private stMATIC;
/// @notice keeps track of total number of operators
uint256 nodeOperatorCounter;
/// @notice min amount allowed to stake per validator.
uint256 public minAmountStake;
/// @notice min HeimdallFees allowed to stake per validator.
uint256 public minHeimdallFees;
/// @notice commision rate applied to all the operators.
uint256 public commissionRate;
/// @notice allows restake.
bool public allowsRestake;
/// @notice default max delgation limit.
uint256 public defaultMaxDelegateLimit;
/// @notice This stores the operators ids.
uint256[] private operatorIds;
/// @notice Mapping of all owners with node operator id. Mapping is used to be able to
/// extend the struct.
mapping(address => uint256) private operatorOwners;
/// @notice Mapping of all node operators. Mapping is used to be able to extend the struct.
mapping(uint256 => NodeOperator) private operators;
/// --------------------------- Modifiers-----------------------------------
/// @notice Check if the msg.sender has permission.
/// @param _role role needed to call function.
modifier userHasRole(bytes32 _role) {
checkCondition(hasRole(_role, msg.sender), "unauthorized");
_;
}
/// @notice Check if the amount is inbound.
/// @param _amount amount to stake.
modifier checkStakeAmount(uint256 _amount) {
checkCondition(_amount >= minAmountStake, "Invalid amount");
_;
}
/// @notice Check if the heimdall fee is inbound.
/// @param _heimdallFee heimdall fee.
modifier checkHeimdallFees(uint256 _heimdallFee) {
checkCondition(_heimdallFee >= minHeimdallFees, "Invalid fees");
_;
}
/// @notice Check if the maxDelegateLimit is less or equal to 10 Billion.
/// @param _maxDelegateLimit max delegate limit.
modifier checkMaxDelegationLimit(uint256 _maxDelegateLimit) {
checkCondition(
_maxDelegateLimit <= 10000000000 ether,
"Max amount <= 10B"
);
_;
}
/// @notice Check if the rewardAddress is already used.
/// @param _rewardAddress new reward address.
modifier checkIfRewardAddressIsUsed(address _rewardAddress) {
checkCondition(
operatorOwners[_rewardAddress] == 0 && _rewardAddress != address(0),
"Address used"
);
_;
}
/// -------------------------- initialize ----------------------------------
/// @notice Initialize the NodeOperator contract.
function initialize(
address _validatorFactory,
address _stakeManager,
address _polygonERC20,
address _stMATIC
) external initializer {
__Pausable_init();
__AccessControl_init();
__ReentrancyGuard_init();
validatorFactory = _validatorFactory;
stakeManager = _stakeManager;
polygonERC20 = _polygonERC20;
stMATIC = _stMATIC;
minAmountStake = 10 * 10**18;
minHeimdallFees = 20 * 10**18;
defaultMaxDelegateLimit = 10 ether;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(REMOVE_OPERATOR_ROLE, msg.sender);
_setupRole(PAUSE_OPERATOR_ROLE, msg.sender);
_setupRole(DAO_ROLE, msg.sender);
}
/// ----------------------------- API --------------------------------------
/// @notice Add a new node operator to the system.
/// @dev The operator life cycle starts when we call the addOperator
/// func allows adding a new operator. During this call, a new validatorProxy is
/// deployed by the ValidatorFactory which we can use later to interact with the
/// Polygon StakeManager. At the end of this call, the status of the operator
/// will be INACTIVE.
/// @param _name the node operator name.
/// @param _rewardAddress address used for ACL and receive rewards.
/// @param _signerPubkey public key used on heimdall len 64 bytes.
function addOperator(
string memory _name,
address _rewardAddress,
bytes memory _signerPubkey
)
external
override
whenNotPaused
userHasRole(DAO_ROLE)
checkIfRewardAddressIsUsed(_rewardAddress)
{
nodeOperatorCounter++;
address validatorProxy = IValidatorFactory(validatorFactory).create();
operators[nodeOperatorCounter] = NodeOperator({
status: NodeOperatorStatus.INACTIVE,
name: _name,
rewardAddress: _rewardAddress,
validatorId: 0,
signerPubkey: _signerPubkey,
validatorShare: address(0),
validatorProxy: validatorProxy,
commissionRate: commissionRate,
maxDelegateLimit: defaultMaxDelegateLimit
});
operatorIds.push(nodeOperatorCounter);
totalNodeOperators++;
operatorOwners[_rewardAddress] = nodeOperatorCounter;
emit AddOperator(nodeOperatorCounter);
}
/// @notice Allows to stop an operator from the system.
/// @param _operatorId the node operator id.
function stopOperator(uint256 _operatorId)
external
override
{
(, NodeOperator storage no) = getOperator(_operatorId);
require(
no.rewardAddress == msg.sender || hasRole(DAO_ROLE, msg.sender), "unauthorized"
);
NodeOperatorStatus status = getOperatorStatus(no);
checkCondition(
status == NodeOperatorStatus.ACTIVE || status == NodeOperatorStatus.INACTIVE ||
status == NodeOperatorStatus.JAILED
, "Invalid status");
if (status == NodeOperatorStatus.INACTIVE) {
no.status = NodeOperatorStatus.EXIT;
} else {
IStMATIC(stMATIC).withdrawTotalDelegated(no.validatorShare);
no.status = NodeOperatorStatus.STOPPED;
}
emit StopOperator(_operatorId);
}
/// @notice Allows to remove an operator from the system.when the operator status is
/// set to EXIT the GOVERNANCE can call the removeOperator func to delete the operator,
/// and the validatorProxy used to interact with the Polygon stakeManager.
/// @param _operatorId the node operator id.
function removeOperator(uint256 _operatorId)
external
override
whenNotPaused
userHasRole(REMOVE_OPERATOR_ROLE)
{
(, NodeOperator storage no) = getOperator(_operatorId);
checkCondition(no.status == NodeOperatorStatus.EXIT, "Invalid status");
// update the operatorIds array by removing the operator id.
for (uint256 idx = 0; idx < operatorIds.length - 1; idx++) {
if (_operatorId == operatorIds[idx]) {
operatorIds[idx] = operatorIds[operatorIds.length - 1];
break;
}
}
operatorIds.pop();
totalNodeOperators--;
IValidatorFactory(validatorFactory).remove(no.validatorProxy);
delete operatorOwners[no.rewardAddress];
delete operators[_operatorId];
emit RemoveOperator(_operatorId);
}
/// @notice Allows a validator that was already staked on the polygon stake manager
/// to join the PoLido protocol.
function joinOperator() external override whenNotPaused {
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
checkCondition(
getOperatorStatus(no) == NodeOperatorStatus.INACTIVE,
"Invalid status"
);
IStakeManager sm = IStakeManager(stakeManager);
uint256 validatorId = sm.getValidatorId(msg.sender);
checkCondition(validatorId != 0, "ValidatorId=0");
IStakeManager.Validator memory poValidator = sm.validators(validatorId);
checkCondition(
poValidator.contractAddress != address(0),
"Validator has no ValidatorShare"
);
checkCondition(
(poValidator.status == IStakeManager.Status.Active
) && poValidator.deactivationEpoch == 0 ,
"Validator isn't ACTIVE"
);
checkCondition(
poValidator.signer ==
address(uint160(uint256(keccak256(no.signerPubkey)))),
"Invalid Signer"
);
IValidator(no.validatorProxy).join(
validatorId,
sm.NFTContract(),
msg.sender,
no.commissionRate,
stakeManager
);
no.validatorId = validatorId;
address validatorShare = sm.getValidatorContract(validatorId);
no.validatorShare = validatorShare;
emit JoinOperator(operatorId);
}
/// ------------------------Stake Manager API-------------------------------
/// @notice Allows to stake a validator on the Polygon stakeManager contract.
/// @dev The stake func allows each operator's owner to stake, but before that,
/// the owner has to approve the amount + Heimdall fees to the ValidatorProxy.
/// At the end of this call, the status of the operator is set to ACTIVE.
/// @param _amount amount to stake.
/// @param _heimdallFee heimdall fees.
function stake(uint256 _amount, uint256 _heimdallFee)
external
override
whenNotPaused
checkStakeAmount(_amount)
checkHeimdallFees(_heimdallFee)
{
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
checkCondition(
getOperatorStatus(no) == NodeOperatorStatus.INACTIVE,
"Invalid status"
);
(uint256 validatorId, address validatorShare) = IValidator(
no.validatorProxy
).stake(
msg.sender,
_amount,
_heimdallFee,
true,
no.signerPubkey,
no.commissionRate,
stakeManager,
polygonERC20
);
no.validatorId = validatorId;
no.validatorShare = validatorShare;
emit StakeOperator(operatorId, _amount, _heimdallFee);
}
/// @notice Allows to restake Matics to Polygon stakeManager
/// @dev restake allows an operator's owner to increase the total staked amount
/// on Polygon. The owner has to approve the amount to the ValidatorProxy then make
/// a call.
/// @param _amount amount to stake.
function restake(uint256 _amount, bool _restakeRewards)
external
override
whenNotPaused
{
checkCondition(allowsRestake, "Restake is disabled");
if (_amount == 0) {
revert("Amount is ZERO");
}
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
checkCondition(
getOperatorStatus(no) == NodeOperatorStatus.ACTIVE,
"Invalid status"
);
IValidator(no.validatorProxy).restake(
msg.sender,
no.validatorId,
_amount,
_restakeRewards,
stakeManager,
polygonERC20
);
emit RestakeOperator(operatorId, _amount, _restakeRewards);
}
/// @notice Unstake a validator from the Polygon stakeManager contract.
/// @dev when the operators's owner wants to quite the PoLido protocol he can call
/// the unstake func, in this case, the operator status is set to UNSTAKED.
function unstake() external override whenNotPaused {
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
NodeOperatorStatus status = getOperatorStatus(no);
checkCondition(
status == NodeOperatorStatus.ACTIVE ||
status == NodeOperatorStatus.JAILED ||
status == NodeOperatorStatus.EJECTED,
"Invalid status"
);
if (status == NodeOperatorStatus.ACTIVE) {
IValidator(no.validatorProxy).unstake(no.validatorId, stakeManager);
}
_unstake(operatorId, no);
}
/// @notice The DAO unstake the operator if it was unstaked by the stakeManager.
/// @dev when the operator was unstaked by the stage Manager the DAO can use this
/// function to update the operator status and also withdraw the delegated tokens,
/// without waiting for the owner to call the unstake function
/// @param _operatorId operator id.
function unstake(uint256 _operatorId) external userHasRole(DAO_ROLE) {
NodeOperator storage no = operators[_operatorId];
NodeOperatorStatus status = getOperatorStatus(no);
checkCondition(status == NodeOperatorStatus.EJECTED, "Invalid status");
_unstake(_operatorId, no);
}
function _unstake(uint256 _operatorId, NodeOperator storage no)
private
whenNotPaused
{
IStMATIC(stMATIC).withdrawTotalDelegated(no.validatorShare);
no.status = NodeOperatorStatus.UNSTAKED;
emit UnstakeOperator(_operatorId);
}
/// @notice Allows the operator's owner to migrate the validator ownership to rewardAddress.
/// This can be done only in the case where this operator was stopped by the DAO.
function migrate() external override nonReentrant {
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
checkCondition(no.status == NodeOperatorStatus.STOPPED, "Invalid status");
IValidator(no.validatorProxy).migrate(
no.validatorId,
IStakeManager(stakeManager).NFTContract(),
no.rewardAddress
);
no.status = NodeOperatorStatus.EXIT;
emit MigrateOperator(operatorId);
}
/// @notice Allows to unjail the validator and turn his status from UNSTAKED to ACTIVE.
/// @dev when an operator is JAILED the owner can switch back and stake the
/// operator by calling the unjail func, in this case, the operator status is set
/// to back ACTIVE.
function unjail() external override whenNotPaused {
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
checkCondition(
getOperatorStatus(no) == NodeOperatorStatus.JAILED,
"Invalid status"
);
IValidator(no.validatorProxy).unjail(no.validatorId, stakeManager);
emit Unjail(operatorId);
}
/// @notice Allows to top up heimdall fees.
/// @dev the operator's owner can topUp the heimdall fees by calling the
/// topUpForFee, but before that node operator needs to approve the amount of heimdall
/// fees to his validatorProxy.
/// @param _heimdallFee amount
function topUpForFee(uint256 _heimdallFee)
external
override
whenNotPaused
checkHeimdallFees(_heimdallFee)
{
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
checkCondition(
getOperatorStatus(no) == NodeOperatorStatus.ACTIVE,
"Invalid status"
);
IValidator(no.validatorProxy).topUpForFee(
msg.sender,
_heimdallFee,
stakeManager,
polygonERC20
);
emit TopUpHeimdallFees(operatorId, _heimdallFee);
}
/// @notice Allows to unstake staked tokens after withdraw delay.
/// @dev after the unstake the operator and waiting for the Polygon withdraw_delay
/// the owner can transfer back his staked balance by calling
/// unsttakeClaim, after that the operator status is set to CLAIMED
function unstakeClaim() external override whenNotPaused {
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
checkCondition(
getOperatorStatus(no) == NodeOperatorStatus.UNSTAKED,
"Invalid status"
);
uint256 amount = IValidator(no.validatorProxy).unstakeClaim(
no.validatorId,
msg.sender,
stakeManager,
polygonERC20
);
no.status = NodeOperatorStatus.CLAIMED;
emit UnstakeClaim(operatorId, amount);
}
/// @notice Allows withdraw heimdall fees
/// @dev the operator's owner can claim the heimdall fees.
/// func, after that the operator status is set to EXIT.
/// @param _accumFeeAmount accumulated heimdall fees
/// @param _index index
/// @param _proof proof
function claimFee(
uint256 _accumFeeAmount,
uint256 _index,
bytes memory _proof
) external override whenNotPaused {
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
checkCondition(
no.status == NodeOperatorStatus.CLAIMED,
"Invalid status"
);
IValidator(no.validatorProxy).claimFee(
_accumFeeAmount,
_index,
_proof,
no.rewardAddress,
stakeManager,
polygonERC20
);
no.status = NodeOperatorStatus.EXIT;
emit ClaimFee(operatorId);
}
/// @notice Allows the operator's owner to withdraw rewards.
function withdrawRewards() external override whenNotPaused {
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
checkCondition(
getOperatorStatus(no) == NodeOperatorStatus.ACTIVE,
"Invalid status"
);
address rewardAddress = no.rewardAddress;
uint256 rewards = IValidator(no.validatorProxy).withdrawRewards(
no.validatorId,
rewardAddress,
stakeManager,
polygonERC20
);
emit WithdrawRewards(operatorId, rewardAddress, rewards);
}
/// @notice Allows the operator's owner to update signer publickey.
/// @param _signerPubkey new signer publickey
function updateSigner(bytes memory _signerPubkey)
external
override
whenNotPaused
{
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
NodeOperatorStatus status = getOperatorStatus(no);
checkCondition(
status == NodeOperatorStatus.ACTIVE || status == NodeOperatorStatus.INACTIVE,
"Invalid status"
);
if (no.status == NodeOperatorStatus.ACTIVE) {
IValidator(no.validatorProxy).updateSigner(
no.validatorId,
_signerPubkey,
stakeManager
);
}
no.signerPubkey = _signerPubkey;
emit UpdateSignerPubkey(operatorId);
}
/// @notice Allows the operator owner to update the name.
/// @param _name new operator name.
function setOperatorName(string memory _name)
external
override
whenNotPaused
{
// uint256 operatorId = getOperatorId(msg.sender);
// NodeOperator storage no = operators[operatorId];
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
NodeOperatorStatus status = getOperatorStatus(no);
checkCondition(
status == NodeOperatorStatus.ACTIVE || status == NodeOperatorStatus.INACTIVE,
"Invalid status"
);
no.name = _name;
emit NewName(operatorId, _name);
}
/// @notice Allows the operator owner to update the rewardAddress.
/// @param _rewardAddress new reward address.
function setOperatorRewardAddress(address _rewardAddress)
external
override
whenNotPaused
checkIfRewardAddressIsUsed(_rewardAddress)
{
(uint256 operatorId, NodeOperator storage no) = getOperator(0);
no.rewardAddress = _rewardAddress;
operatorOwners[_rewardAddress] = operatorId;
delete operatorOwners[msg.sender];
emit NewRewardAddress(operatorId, _rewardAddress);
}
/// -------------------------------DAO--------------------------------------
/// @notice Allows the DAO to set the operator defaultMaxDelegateLimit.
/// @param _defaultMaxDelegateLimit default max delegation amount.
function setDefaultMaxDelegateLimit(uint256 _defaultMaxDelegateLimit)
external
override
userHasRole(DAO_ROLE)
checkMaxDelegationLimit(_defaultMaxDelegateLimit)
{
defaultMaxDelegateLimit = _defaultMaxDelegateLimit;
}
/// @notice Allows the DAO to set the operator maxDelegateLimit.
/// @param _operatorId operator id.
/// @param _maxDelegateLimit max amount to delegate .
function setMaxDelegateLimit(uint256 _operatorId, uint256 _maxDelegateLimit)
external
override
userHasRole(DAO_ROLE)
checkMaxDelegationLimit(_maxDelegateLimit)
{
(, NodeOperator storage no) = getOperator(_operatorId);
no.maxDelegateLimit = _maxDelegateLimit;
}
/// @notice Allows to set the commission rate used.
function setCommissionRate(uint256 _commissionRate)
external
override
userHasRole(DAO_ROLE)
{
commissionRate = _commissionRate;
}
/// @notice Allows the dao to update commission rate for an operator.
/// @param _operatorId id of the operator
/// @param _newCommissionRate new commission rate
function updateOperatorCommissionRate(
uint256 _operatorId,
uint256 _newCommissionRate
) external override userHasRole(DAO_ROLE) {
(, NodeOperator storage no) = getOperator(_operatorId);
checkCondition(
no.rewardAddress != address(0) ||
no.status == NodeOperatorStatus.ACTIVE,
"Invalid status"
);
if (no.status == NodeOperatorStatus.ACTIVE) {
IValidator(no.validatorProxy).updateCommissionRate(
no.validatorId,
_newCommissionRate,
stakeManager
);
}
no.commissionRate = _newCommissionRate;
emit UpdateCommissionRate(_operatorId, _newCommissionRate);
}
/// @notice Allows to update the stake amount and heimdall fees
/// @param _minAmountStake min amount to stake
/// @param _minHeimdallFees min amount of heimdall fees
function setStakeAmountAndFees(
uint256 _minAmountStake,
uint256 _minHeimdallFees
)
external
override
userHasRole(DAO_ROLE)
checkStakeAmount(_minAmountStake)
checkHeimdallFees(_minHeimdallFees)
{
minAmountStake = _minAmountStake;
minHeimdallFees = _minHeimdallFees;
}
/// @notice Allows to pause the contract.
function togglePause() external override userHasRole(PAUSE_OPERATOR_ROLE) {
paused() ? _unpause() : _pause();
}
/// @notice Allows to toggle restake.
function setRestake(bool _restake) external override userHasRole(DAO_ROLE) {
allowsRestake = _restake;
}
/// @notice Allows to set the StMATIC contract address.
function setStMATIC(address _stMATIC)
external
override
userHasRole(DAO_ROLE)
{
stMATIC = _stMATIC;
}
/// @notice Allows to set the validator factory contract address.
function setValidatorFactory(address _validatorFactory)
external
override
userHasRole(DAO_ROLE)
{
validatorFactory = _validatorFactory;
}
/// @notice Allows to set the stake manager contract address.
function setStakeManager(address _stakeManager)
external
override
userHasRole(DAO_ROLE)
{
stakeManager = _stakeManager;
}
/// @notice Allows to set the contract version.
/// @param _version contract version
function setVersion(string memory _version)
external
override
userHasRole(DEFAULT_ADMIN_ROLE)
{
version = _version;
}
/// @notice Allows to get a node operator by msg.sender.
/// @param _owner a valid address of an operator owner, if not set msg.sender will be used.
/// @return op returns a node operator.
function getNodeOperator(address _owner)
external
view
returns (NodeOperator memory)
{
uint256 operatorId = operatorOwners[_owner];
return _getNodeOperator(operatorId);
}
/// @notice Allows to get a node operator by _operatorId.
/// @param _operatorId the id of the operator.
/// @return op returns a node operator.
function getNodeOperator(uint256 _operatorId)
external
view
returns (NodeOperator memory)
{
return _getNodeOperator(_operatorId);
}
function _getNodeOperator(uint256 _operatorId)
private
view
returns (NodeOperator memory)
{
(, NodeOperator memory nodeOperator) = getOperator(_operatorId);
nodeOperator.status = getOperatorStatus(nodeOperator);
return nodeOperator;
}
function getOperatorStatus(NodeOperator memory _op)
private
view
returns (NodeOperatorStatus res)
{
if (_op.status == NodeOperatorStatus.STOPPED) {
res = NodeOperatorStatus.STOPPED;
} else if (_op.status == NodeOperatorStatus.CLAIMED) {
res = NodeOperatorStatus.CLAIMED;
} else if (_op.status == NodeOperatorStatus.EXIT) {
res = NodeOperatorStatus.EXIT;
} else if (_op.status == NodeOperatorStatus.UNSTAKED) {
res = NodeOperatorStatus.UNSTAKED;
} else {
IStakeManager.Validator memory v = IStakeManager(stakeManager)
.validators(_op.validatorId);
if (
v.status == IStakeManager.Status.Active &&
v.deactivationEpoch == 0
) {
res = NodeOperatorStatus.ACTIVE;
} else if (
(
v.status == IStakeManager.Status.Active ||
v.status == IStakeManager.Status.Locked
) &&
v.deactivationEpoch != 0
) {
res = NodeOperatorStatus.EJECTED;
} else if (
v.status == IStakeManager.Status.Locked &&
v.deactivationEpoch == 0
) {
res = NodeOperatorStatus.JAILED;
} else {
res = NodeOperatorStatus.INACTIVE;
}
}
}
/// @notice Allows to get a validator share address.
/// @param _operatorId the id of the operator.
/// @return va returns a stake manager validator.
function getValidatorShare(uint256 _operatorId)
external
view
returns (address)
{
(, NodeOperator memory op) = getOperator(_operatorId);
return op.validatorShare;
}
/// @notice Allows to get a validator from stake manager.
/// @param _operatorId the id of the operator.
/// @return va returns a stake manager validator.
function getValidator(uint256 _operatorId)
external
view
returns (IStakeManager.Validator memory va)
{
(, NodeOperator memory op) = getOperator(_operatorId);
va = IStakeManager(stakeManager).validators(op.validatorId);
}
/// @notice Allows to get a validator from stake manager.
/// @param _owner user address.
/// @return va returns a stake manager validator.
function getValidator(address _owner)
external
view
returns (IStakeManager.Validator memory va)
{
(, NodeOperator memory op) = getOperator(operatorOwners[_owner]);
va = IStakeManager(stakeManager).validators(op.validatorId);
}
/// @notice Get the stMATIC contract addresses
function getContracts()
external
view
override
returns (
address _validatorFactory,
address _stakeManager,
address _polygonERC20,
address _stMATIC
)
{
_validatorFactory = validatorFactory;
_stakeManager = stakeManager;
_polygonERC20 = polygonERC20;
_stMATIC = stMATIC;
}
/// @notice Get the global state
function getState()
external
view
override
returns (
uint256 _totalNodeOperator,
uint256 _totalInactiveNodeOperator,
uint256 _totalActiveNodeOperator,
uint256 _totalStoppedNodeOperator,
uint256 _totalUnstakedNodeOperator,
uint256 _totalClaimedNodeOperator,
uint256 _totalExitNodeOperator,
uint256 _totalJailedNodeOperator,
uint256 _totalEjectedNodeOperator
)
{
uint256 operatorIdsLength = operatorIds.length;
_totalNodeOperator = operatorIdsLength;
for (uint256 idx = 0; idx < operatorIdsLength; idx++) {
uint256 operatorId = operatorIds[idx];
NodeOperator memory op = operators[operatorId];
NodeOperatorStatus status = getOperatorStatus(op);
if (status == NodeOperatorStatus.INACTIVE) {
_totalInactiveNodeOperator++;
} else if (status == NodeOperatorStatus.ACTIVE) {
_totalActiveNodeOperator++;
} else if (status == NodeOperatorStatus.STOPPED) {
_totalStoppedNodeOperator++;
} else if (status == NodeOperatorStatus.UNSTAKED) {
_totalUnstakedNodeOperator++;
} else if (status == NodeOperatorStatus.CLAIMED) {
_totalClaimedNodeOperator++;
} else if (status == NodeOperatorStatus.JAILED) {
_totalJailedNodeOperator++;
} else if (status == NodeOperatorStatus.EJECTED) {
_totalEjectedNodeOperator++;
} else {
_totalExitNodeOperator++;
}
}
}
/// @notice Get operatorIds.
function getOperatorIds()
external
view
override
returns (uint256[] memory)
{
return operatorIds;
}
/// @notice Returns an operatorInfo list.
/// @param _allWithStake if true return all operators with ACTIVE, EJECTED, JAILED.
/// @param _delegation if true return all operators that delegation is set to true.
/// @return Returns a list of operatorInfo.
function getOperatorInfos(
bool _delegation,
bool _allWithStake
) external view override returns (Operator.OperatorInfo[] memory) {
Operator.OperatorInfo[]
memory operatorInfos = new Operator.OperatorInfo[](
totalNodeOperators
);
uint256 length = operatorIds.length;
uint256 index;
for (uint256 idx = 0; idx < length; idx++) {
uint256 operatorId = operatorIds[idx];
NodeOperator storage no = operators[operatorId];
NodeOperatorStatus status = getOperatorStatus(no);
// if operator status is not ACTIVE we continue. But, if _allWithStake is true
// we include EJECTED and JAILED operators.
if (
status != NodeOperatorStatus.ACTIVE &&
!(_allWithStake &&
(status == NodeOperatorStatus.EJECTED ||
status == NodeOperatorStatus.JAILED))
) continue;
// if true we check if the operator delegation is true.
if (_delegation) {
if (!IValidatorShare(no.validatorShare).delegation()) continue;
}
operatorInfos[index] = Operator.OperatorInfo({
operatorId: operatorId,
validatorShare: no.validatorShare,
maxDelegateLimit: no.maxDelegateLimit,
rewardAddress: no.rewardAddress
});
index++;
}
if (index != totalNodeOperators) {
Operator.OperatorInfo[]
memory operatorInfosOut = new Operator.OperatorInfo[](index);
for (uint256 i = 0; i < index; i++) {
operatorInfosOut[i] = operatorInfos[i];
}
return operatorInfosOut;
}
return operatorInfos;
}
/// @notice Checks condition and displays the message
/// @param _condition a condition
/// @param _message message to display
function checkCondition(bool _condition, string memory _message)
private
pure
{
require(_condition, _message);
}
/// @notice Retrieve the operator struct based on the operatorId
/// @param _operatorId id of the operator
/// @return NodeOperator structure
function getOperator(uint256 _operatorId)
private
view
returns (uint256, NodeOperator storage)
{
if (_operatorId == 0) {
_operatorId = getOperatorId(msg.sender);
}
NodeOperator storage no = operators[_operatorId];
require(no.rewardAddress != address(0), "Operator not found");
return (_operatorId, no);
}
/// @notice Retrieve the operator struct based on the operator owner address
/// @param _user address of the operator owner
/// @return NodeOperator structure
function getOperatorId(address _user) private view returns (uint256) {
uint256 operatorId = operatorOwners[_user];
checkCondition(operatorId != 0, "Operator not found");
return operatorId;
}
/// -------------------------------Events-----------------------------------
/// @notice A new node operator was added.
/// @param operatorId node operator id.
event AddOperator(uint256 operatorId);
/// @notice A new node operator joined.
/// @param operatorId node operator id.
event JoinOperator(uint256 operatorId);
/// @notice A node operator was removed.
/// @param operatorId node operator id.
event RemoveOperator(uint256 operatorId);
/// @param operatorId node operator id.
event StopOperator(uint256 operatorId);
/// @param operatorId node operator id.
event MigrateOperator(uint256 operatorId);
/// @notice A node operator was staked.
/// @param operatorId node operator id.
event StakeOperator(
uint256 operatorId,
uint256 amount,
uint256 heimdallFees
);
/// @notice A node operator restaked.
/// @param operatorId node operator id.
/// @param amount amount to restake.
/// @param restakeRewards restake rewards.
event RestakeOperator(
uint256 operatorId,
uint256 amount,
bool restakeRewards
);
/// @notice A node operator was unstaked.
/// @param operatorId node operator id.
event UnstakeOperator(uint256 operatorId);
/// @notice TopUp heimadall fees.
/// @param operatorId node operator id.
/// @param amount amount.
event TopUpHeimdallFees(uint256 operatorId, uint256 amount);
/// @notice Withdraw rewards.
/// @param operatorId node operator id.
/// @param rewardAddress reward address.
/// @param amount amount.
event WithdrawRewards(
uint256 operatorId,
address rewardAddress,
uint256 amount
);
/// @notice claims unstake.
/// @param operatorId node operator id.
/// @param amount amount.
event UnstakeClaim(uint256 operatorId, uint256 amount);
/// @notice update signer publickey.
/// @param operatorId node operator id.
event UpdateSignerPubkey(uint256 operatorId);
/// @notice claim herimdall fee.
/// @param operatorId node operator id.
event ClaimFee(uint256 operatorId);
/// @notice update commission rate.
event UpdateCommissionRate(uint256 operatorId, uint256 newCommissionRate);
/// @notice Unjail a validator.
event Unjail(uint256 operatorId);
/// @notice update operator name.
event NewName(uint256 operatorId, string name);
/// @notice update operator name.
event NewRewardAddress(uint256 operatorId, address rewardAddress);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "../lib/Operator.sol";
/// @title INodeOperatorRegistry
/// @author 2021 ShardLabs
/// @notice Node operator registry interface
interface INodeOperatorRegistry {
/// @notice Allows to add a new node operator to the system.
/// @param _name the node operator name.
/// @param _rewardAddress public address used for ACL and receive rewards.
/// @param _signerPubkey public key used on heimdall len 64 bytes.
function addOperator(
string memory _name,
address _rewardAddress,
bytes memory _signerPubkey
) external;
/// @notice Allows to stop a node operator.
/// @param _operatorId node operator id.
function stopOperator(uint256 _operatorId) external;
/// @notice Allows to remove a node operator from the system.
/// @param _operatorId node operator id.
function removeOperator(uint256 _operatorId) external;
/// @notice Allows a staked validator to join the system.
function joinOperator() external;
/// @notice Allows to stake an operator on the Polygon stakeManager.
/// This function calls Polygon transferFrom so the totalAmount(_amount + _heimdallFee)
/// has to be approved first.
/// @param _amount amount to stake.
/// @param _heimdallFee heimdallFee to stake.
function stake(uint256 _amount, uint256 _heimdallFee) external;
/// @notice Restake Matics for a validator on polygon stake manager.
/// @param _amount amount to stake.
/// @param _restakeRewards restake rewards.
function restake(uint256 _amount, bool _restakeRewards) external;
/// @notice Allows the operator's owner to migrate the NFT. This can be done only
/// if the DAO stopped the operator.
function migrate() external;
/// @notice Allows to unstake an operator from the stakeManager. After the withdraw_delay
/// the operator owner can call claimStake func to withdraw the staked tokens.
function unstake() external;
/// @notice Allows to topup heimdall fees on polygon stakeManager.
/// @param _heimdallFee amount to topup.
function topUpForFee(uint256 _heimdallFee) external;
/// @notice Allows to claim staked tokens on the stake Manager after the end of the
/// withdraw delay
function unstakeClaim() external;
/// @notice Allows an owner to withdraw rewards from the stakeManager.
function withdrawRewards() external;
/// @notice Allows to update the signer pubkey
/// @param _signerPubkey update signer public key
function updateSigner(bytes memory _signerPubkey) external;
/// @notice Allows to claim the heimdall fees staked by the owner of the operator
/// @param _accumFeeAmount accumulated fees amount
/// @param _index index
/// @param _proof proof
function claimFee(
uint256 _accumFeeAmount,
uint256 _index,
bytes memory _proof
) external;
/// @notice Allows to unjail a validator and switch from UNSTAKE status to STAKED
function unjail() external;
/// @notice Allows an operator's owner to set the operator name.
function setOperatorName(string memory _name) external;
/// @notice Allows an operator's owner to set the operator rewardAddress.
function setOperatorRewardAddress(address _rewardAddress) external;
/// @notice Allows the DAO to set _defaultMaxDelegateLimit.
function setDefaultMaxDelegateLimit(uint256 _defaultMaxDelegateLimit)
external;
/// @notice Allows the DAO to set _maxDelegateLimit for an operator.
function setMaxDelegateLimit(uint256 _operatorId, uint256 _maxDelegateLimit)
external;
/// @notice Allows the DAO to set _commissionRate.
function setCommissionRate(uint256 _commissionRate) external;
/// @notice Allows the DAO to set _commissionRate for an operator.
/// @param _operatorId id of the operator
/// @param _newCommissionRate new commission rate
function updateOperatorCommissionRate(
uint256 _operatorId,
uint256 _newCommissionRate
) external;
/// @notice Allows the DAO to set _minAmountStake and _minHeimdallFees.
function setStakeAmountAndFees(
uint256 _minAmountStake,
uint256 _minHeimdallFees
) external;
/// @notice Allows to pause/unpause the node operator contract.
function togglePause() external;
/// @notice Allows the DAO to enable/disable restake.
function setRestake(bool _restake) external;
/// @notice Allows the DAO to set stMATIC contract.
function setStMATIC(address _stMATIC) external;
/// @notice Allows the DAO to set validator factory contract.
function setValidatorFactory(address _validatorFactory) external;
/// @notice Allows the DAO to set stake manager contract.
function setStakeManager(address _stakeManager) external;
/// @notice Allows to set contract version.
function setVersion(string memory _version) external;
/// @notice Get the stMATIC contract addresses
function getContracts()
external
view
returns (
address _validatorFactory,
address _stakeManager,
address _polygonERC20,
address _stMATIC
);
/// @notice Allows to get stats.
function getState()
external
view
returns (
uint256 _totalNodeOperator,
uint256 _totalInactiveNodeOperator,
uint256 _totalActiveNodeOperator,
uint256 _totalStoppedNodeOperator,
uint256 _totalUnstakedNodeOperator,
uint256 _totalClaimedNodeOperator,
uint256 _totalExitNodeOperator,
uint256 _totalSlashedNodeOperator,
uint256 _totalEjectedNodeOperator
);
/// @notice Allows to get a list of operatorInfo.
function getOperatorInfos(bool _delegation, bool _allActive)
external
view
returns (Operator.OperatorInfo[] memory);
/// @notice Allows to get all the operator ids.
function getOperatorIds() external view returns (uint256[] memory);
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "../Validator.sol";
/// @title IValidatorFactory.
/// @author 2021 ShardLabs
interface IValidatorFactory {
/// @notice Deploy a new validator proxy contract.
/// @return return the address of the deployed contract.
function create() external returns (address);
/// @notice Remove a validator proxy from the validators.
function remove(address _validatorProxy) external;
/// @notice Set the node operator contract address.
function setOperator(address _operator) external;
/// @notice Set validator implementation contract address.
function setValidatorImplementation(address _validatorImplementation)
external;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "../Validator.sol";
/// @title IValidator.
/// @author 2021 ShardLabs
/// @notice Validator interface.
interface IValidator {
/// @notice Allows to stake a validator on the Polygon stakeManager contract.
/// @dev Stake a validator on the Polygon stakeManager contract.
/// @param _sender msg.sender.
/// @param _amount amount to stake.
/// @param _heimdallFee herimdall fees.
/// @param _acceptDelegation accept delegation.
/// @param _signerPubkey signer public key used on the heimdall.
/// @param _commisionRate commision rate of a validator
function stake(
address _sender,
uint256 _amount,
uint256 _heimdallFee,
bool _acceptDelegation,
bytes memory _signerPubkey,
uint256 _commisionRate,
address stakeManager,
address polygonERC20
) external returns (uint256, address);
/// @notice Restake Matics for a validator on polygon stake manager.
/// @param sender operator owner which approved tokens to the validato contract.
/// @param validatorId validator id.
/// @param amount amount to stake.
/// @param stakeRewards restake rewards.
/// @param stakeManager stake manager address
/// @param polygonERC20 address of the MATIC token
function restake(
address sender,
uint256 validatorId,
uint256 amount,
bool stakeRewards,
address stakeManager,
address polygonERC20
) external;
/// @notice Unstake a validator from the Polygon stakeManager contract.
/// @dev Unstake a validator from the Polygon stakeManager contract by passing the validatorId
/// @param _validatorId validatorId.
/// @param _stakeManager address of the stake manager
function unstake(uint256 _validatorId, address _stakeManager) external;
/// @notice Allows to top up heimdall fees.
/// @param _heimdallFee amount
/// @param _sender msg.sender
/// @param _stakeManager stake manager address
/// @param _polygonERC20 address of the MATIC token
function topUpForFee(
address _sender,
uint256 _heimdallFee,
address _stakeManager,
address _polygonERC20
) external;
/// @notice Allows to withdraw rewards from the validator.
/// @dev Allows to withdraw rewards from the validator using the _validatorId. Only the
/// owner can request withdraw in this the owner is this contract.
/// @param _validatorId validator id.
/// @param _rewardAddress user address used to transfer the staked tokens.
/// @param _stakeManager stake manager address
/// @param _polygonERC20 address of the MATIC token
/// @return Returns the amount transfered to the user.
function withdrawRewards(
uint256 _validatorId,
address _rewardAddress,
address _stakeManager,
address _polygonERC20
) external returns (uint256);
/// @notice Allows to claim staked tokens on the stake Manager after the end of the
/// withdraw delay
/// @param _validatorId validator id.
/// @param _rewardAddress user address used to transfer the staked tokens.
/// @return Returns the amount transfered to the user.
function unstakeClaim(
uint256 _validatorId,
address _rewardAddress,
address _stakeManager,
address _polygonERC20
) external returns (uint256);
/// @notice Allows to update the signer pubkey
/// @param _validatorId validator id
/// @param _signerPubkey update signer public key
/// @param _stakeManager stake manager address
function updateSigner(
uint256 _validatorId,
bytes memory _signerPubkey,
address _stakeManager
) external;
/// @notice Allows to claim the heimdall fees.
/// @param _accumFeeAmount accumulated fees amount
/// @param _index index
/// @param _proof proof
/// @param _ownerRecipient owner recipient
/// @param _stakeManager stake manager address
/// @param _polygonERC20 address of the MATIC token
function claimFee(
uint256 _accumFeeAmount,
uint256 _index,
bytes memory _proof,
address _ownerRecipient,
address _stakeManager,
address _polygonERC20
) external;
/// @notice Allows to update the commision rate of a validator
/// @param _validatorId operator id
/// @param _newCommissionRate commission rate
/// @param _stakeManager stake manager address
function updateCommissionRate(
uint256 _validatorId,
uint256 _newCommissionRate,
address _stakeManager
) external;
/// @notice Allows to unjail a validator.
/// @param _validatorId operator id
function unjail(uint256 _validatorId, address _stakeManager) external;
/// @notice Allows to migrate the ownership to an other user.
/// @param _validatorId operator id.
/// @param _stakeManagerNFT stake manager nft contract.
/// @param _rewardAddress reward address.
function migrate(
uint256 _validatorId,
address _stakeManagerNFT,
address _rewardAddress
) external;
/// @notice Allows a validator that was already staked on the polygon stake manager
/// to join the PoLido protocol.
/// @param _validatorId validator id
/// @param _stakeManagerNFT address of the staking NFT
/// @param _rewardAddress address that will receive the rewards from staking
/// @param _newCommissionRate commission rate
/// @param _stakeManager address of the stake manager
function join(
uint256 _validatorId,
address _stakeManagerNFT,
address _rewardAddress,
uint256 _newCommissionRate,
address _stakeManager
) external;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./IValidatorShare.sol";
import "./INodeOperatorRegistry.sol";
import "./INodeOperatorRegistry.sol";
import "./IStakeManager.sol";
import "./IPoLidoNFT.sol";
import "./IFxStateRootTunnel.sol";
/// @title StMATIC interface.
/// @author 2021 ShardLabs
interface IStMATIC is IERC20Upgradeable {
struct RequestWithdraw {
uint256 amount2WithdrawFromStMATIC;
uint256 validatorNonce;
uint256 requestEpoch;
address validatorAddress;
}
struct FeeDistribution {
uint8 dao;
uint8 operators;
uint8 insurance;
}
function withdrawTotalDelegated(address _validatorShare) external;
function nodeOperatorRegistry() external returns (INodeOperatorRegistry);
function entityFees()
external
returns (
uint8,
uint8,
uint8
);
function getMaticFromTokenId(uint256 _tokenId)
external
view
returns (uint256);
function stakeManager() external view returns (IStakeManager);
function poLidoNFT() external view returns (IPoLidoNFT);
function fxStateRootTunnel() external view returns (IFxStateRootTunnel);
function version() external view returns (string memory);
function dao() external view returns (address);
function insurance() external view returns (address);
function token() external view returns (address);
function lastWithdrawnValidatorId() external view returns (uint256);
function totalBuffered() external view returns (uint256);
function delegationLowerBound() external view returns (uint256);
function rewardDistributionLowerBound() external view returns (uint256);
function reservedFunds() external view returns (uint256);
function submitThreshold() external view returns (uint256);
function submitHandler() external view returns (bool);
function getMinValidatorBalance() external view returns (uint256);
function token2WithdrawRequest(uint256 _requestId)
external
view
returns (
uint256,
uint256,
uint256,
address
);
function DAO() external view returns (bytes32);
function initialize(
address _nodeOperatorRegistry,
address _token,
address _dao,
address _insurance,
address _stakeManager,
address _poLidoNFT,
address _fxStateRootTunnel,
uint256 _submitThreshold
) external;
function submit(uint256 _amount) external returns (uint256);
function requestWithdraw(uint256 _amount) external;
function delegate() external;
function claimTokens(uint256 _tokenId) external;
function distributeRewards() external;
function claimTokens2StMatic(uint256 _tokenId) external;
function togglePause() external;
function getTotalStake(IValidatorShare _validatorShare)
external
view
returns (uint256, uint256);
function getLiquidRewards(IValidatorShare _validatorShare)
external
view
returns (uint256);
function getTotalStakeAcrossAllValidators() external view returns (uint256);
function getTotalPooledMatic() external view returns (uint256);
function convertStMaticToMatic(uint256 _balance)
external
view
returns (
uint256,
uint256,
uint256
);
function convertMaticToStMatic(uint256 _balance)
external
view
returns (
uint256,
uint256,
uint256
);
function setFees(
uint8 _daoFee,
uint8 _operatorsFee,
uint8 _insuranceFee
) external;
function setDaoAddress(address _address) external;
function setInsuranceAddress(address _address) external;
function setNodeOperatorRegistryAddress(address _address) external;
function setDelegationLowerBound(uint256 _delegationLowerBound) external;
function setRewardDistributionLowerBound(
uint256 _rewardDistributionLowerBound
) external;
function setPoLidoNFT(address _poLidoNFT) external;
function setFxStateRootTunnel(address _fxStateRootTunnel) external;
function setSubmitThreshold(uint256 _submitThreshold) external;
function flipSubmitHandler() external;
function setVersion(string calldata _version) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
library Operator {
struct OperatorInfo {
uint256 operatorId;
address validatorShare;
uint256 maxDelegateLimit;
address rewardAddress;
}
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "./interfaces/IStakeManager.sol";
import "./interfaces/IValidator.sol";
import "./interfaces/INodeOperatorRegistry.sol";
/// @title ValidatorImplementation
/// @author 2021 ShardLabs.
/// @notice The validator contract is a simple implementation of the stakeManager API, the
/// ValidatorProxies use this contract to interact with the stakeManager.
/// When a ValidatorProxy calls this implementation the state is copied
/// (owner, implementation, operatorRegistry), then they are used to check if the msg-sender is the
/// node operator contract, and if the validatorProxy implementation match with the current
/// validator contract.
contract Validator is IERC721Receiver, IValidator {
using SafeERC20 for IERC20;
address private implementation;
address private operatorRegistry;
address private validatorFactory;
/// @notice Check if the operator contract is the msg.sender.
modifier isOperatorRegistry() {
require(
msg.sender == operatorRegistry,
"Caller should be the operator contract"
);
_;
}
/// @notice Allows to stake on the Polygon stakeManager contract by
/// calling stakeFor function and set the user as the equal to this validator proxy
/// address.
/// @param _sender the address of the operator-owner that approved Matics.
/// @param _amount the amount to stake with.
/// @param _heimdallFee the heimdall fees.
/// @param _acceptDelegation accept delegation.
/// @param _signerPubkey signer public key used on the heimdall node.
/// @param _commissionRate validator commision rate
/// @return Returns the validatorId and the validatorShare contract address.
function stake(
address _sender,
uint256 _amount,
uint256 _heimdallFee,
bool _acceptDelegation,
bytes memory _signerPubkey,
uint256 _commissionRate,
address _stakeManager,
address _polygonERC20
) external override isOperatorRegistry returns (uint256, address) {
IStakeManager stakeManager = IStakeManager(_stakeManager);
IERC20 polygonERC20 = IERC20(_polygonERC20);
uint256 totalAmount = _amount + _heimdallFee;
polygonERC20.safeTransferFrom(_sender, address(this), totalAmount);
polygonERC20.safeApprove(address(stakeManager), totalAmount);
stakeManager.stakeFor(
address(this),
_amount,
_heimdallFee,
_acceptDelegation,
_signerPubkey
);
uint256 validatorId = stakeManager.getValidatorId(address(this));
address validatorShare = stakeManager.getValidatorContract(validatorId);
if (_commissionRate > 0) {
stakeManager.updateCommissionRate(validatorId, _commissionRate);
}
return (validatorId, validatorShare);
}
/// @notice Restake validator rewards or new Matics validator on stake manager.
/// @param _sender operator's owner that approved tokens to the validator contract.
/// @param _validatorId validator id.
/// @param _amount amount to stake.
/// @param _stakeRewards restake rewards.
/// @param _stakeManager stake manager address
/// @param _polygonERC20 address of the MATIC token
function restake(
address _sender,
uint256 _validatorId,
uint256 _amount,
bool _stakeRewards,
address _stakeManager,
address _polygonERC20
) external override isOperatorRegistry {
if (_amount > 0) {
IERC20 polygonERC20 = IERC20(_polygonERC20);
polygonERC20.safeTransferFrom(_sender, address(this), _amount);
polygonERC20.safeApprove(address(_stakeManager), _amount);
}
IStakeManager(_stakeManager).restake(_validatorId, _amount, _stakeRewards);
}
/// @notice Unstake a validator from the Polygon stakeManager contract.
/// @param _validatorId validatorId.
/// @param _stakeManager address of the stake manager
function unstake(uint256 _validatorId, address _stakeManager)
external
override
isOperatorRegistry
{
// stakeManager
IStakeManager(_stakeManager).unstake(_validatorId);
}
/// @notice Allows a validator to top-up the heimdall fees.
/// @param _sender address that approved the _heimdallFee amount.
/// @param _heimdallFee amount.
/// @param _stakeManager stake manager address
/// @param _polygonERC20 address of the MATIC token
function topUpForFee(
address _sender,
uint256 _heimdallFee,
address _stakeManager,
address _polygonERC20
) external override isOperatorRegistry {
IStakeManager stakeManager = IStakeManager(_stakeManager);
IERC20 polygonERC20 = IERC20(_polygonERC20);
polygonERC20.safeTransferFrom(_sender, address(this), _heimdallFee);
polygonERC20.safeApprove(address(stakeManager), _heimdallFee);
stakeManager.topUpForFee(address(this), _heimdallFee);
}
/// @notice Allows to withdraw rewards from the validator using the _validatorId. Only the
/// owner can request withdraw. The rewards are transfered to the _rewardAddress.
/// @param _validatorId validator id.
/// @param _rewardAddress reward address.
/// @param _stakeManager stake manager address
/// @param _polygonERC20 address of the MATIC token
function withdrawRewards(
uint256 _validatorId,
address _rewardAddress,
address _stakeManager,
address _polygonERC20
) external override isOperatorRegistry returns (uint256) {
IStakeManager(_stakeManager).withdrawRewards(_validatorId);
IERC20 polygonERC20 = IERC20(_polygonERC20);
uint256 balance = polygonERC20.balanceOf(address(this));
polygonERC20.safeTransfer(_rewardAddress, balance);
return balance;
}
/// @notice Allows to unstake the staked tokens (+rewards) and transfer them
/// to the owner rewardAddress.
/// @param _validatorId validator id.
/// @param _rewardAddress rewardAddress address.
/// @param _stakeManager stake manager address
/// @param _polygonERC20 address of the MATIC token
function unstakeClaim(
uint256 _validatorId,
address _rewardAddress,
address _stakeManager,
address _polygonERC20
) external override isOperatorRegistry returns (uint256) {
IStakeManager stakeManager = IStakeManager(_stakeManager);
stakeManager.unstakeClaim(_validatorId);
// polygonERC20
// stakeManager
IERC20 polygonERC20 = IERC20(_polygonERC20);
uint256 balance = polygonERC20.balanceOf(address(this));
polygonERC20.safeTransfer(_rewardAddress, balance);
return balance;
}
/// @notice Allows to update signer publickey.
/// @param _validatorId validator id.
/// @param _signerPubkey new publickey.
/// @param _stakeManager stake manager address
function updateSigner(
uint256 _validatorId,
bytes memory _signerPubkey,
address _stakeManager
) external override isOperatorRegistry {
IStakeManager(_stakeManager).updateSigner(_validatorId, _signerPubkey);
}
/// @notice Allows withdraw heimdall fees.
/// @param _accumFeeAmount accumulated heimdall fees.
/// @param _index index.
/// @param _proof proof.
function claimFee(
uint256 _accumFeeAmount,
uint256 _index,
bytes memory _proof,
address _rewardAddress,
address _stakeManager,
address _polygonERC20
) external override isOperatorRegistry {
IStakeManager stakeManager = IStakeManager(_stakeManager);
stakeManager.claimFee(_accumFeeAmount, _index, _proof);
IERC20 polygonERC20 = IERC20(_polygonERC20);
uint256 balance = polygonERC20.balanceOf(address(this));
polygonERC20.safeTransfer(_rewardAddress, balance);
}
/// @notice Allows to update commission rate of a validator.
/// @param _validatorId validator id.
/// @param _newCommissionRate new commission rate.
/// @param _stakeManager stake manager address
function updateCommissionRate(
uint256 _validatorId,
uint256 _newCommissionRate,
address _stakeManager
) public override isOperatorRegistry {
IStakeManager(_stakeManager).updateCommissionRate(
_validatorId,
_newCommissionRate
);
}
/// @notice Allows to unjail a validator.
/// @param _validatorId validator id
function unjail(uint256 _validatorId, address _stakeManager)
external
override
isOperatorRegistry
{
IStakeManager(_stakeManager).unjail(_validatorId);
}
/// @notice Allows to transfer the validator nft token to the reward address a validator.
/// @param _validatorId operator id.
/// @param _stakeManagerNFT stake manager nft contract.
/// @param _rewardAddress reward address.
function migrate(
uint256 _validatorId,
address _stakeManagerNFT,
address _rewardAddress
) external override isOperatorRegistry {
IERC721 erc721 = IERC721(_stakeManagerNFT);
erc721.approve(_rewardAddress, _validatorId);
erc721.safeTransferFrom(address(this), _rewardAddress, _validatorId);
}
/// @notice Allows a validator that was already staked on the polygon stake manager
/// to join the PoLido protocol.
/// @param _validatorId validator id
/// @param _stakeManagerNFT address of the staking NFT
/// @param _rewardAddress address that will receive the rewards from staking
/// @param _newCommissionRate commission rate
/// @param _stakeManager address of the stake manager
function join(
uint256 _validatorId,
address _stakeManagerNFT,
address _rewardAddress,
uint256 _newCommissionRate,
address _stakeManager
) external override isOperatorRegistry {
IERC721 erc721 = IERC721(_stakeManagerNFT);
erc721.safeTransferFrom(_rewardAddress, address(this), _validatorId);
updateCommissionRate(_validatorId, _newCommissionRate, _stakeManager);
}
/// @notice Allows to get the version of the validator implementation.
/// @return Returns the version.
function version() external pure returns (string memory) {
return "1.0.0";
}
/// @notice Implement @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol interface.
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external pure override returns (bytes4) {
return
bytes4(
keccak256("onERC721Received(address,address,uint256,bytes)")
);
}
}
// 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 (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/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/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-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
/// @title polygon stake manager interface.
/// @author 2021 ShardLabs
/// @notice User to interact with the polygon stake manager.
interface IStakeManager {
/// @notice Stake a validator on polygon stake manager.
/// @param user user that own the validator in our case the validator contract.
/// @param amount amount to stake.
/// @param heimdallFee heimdall fees.
/// @param acceptDelegation accept delegation.
/// @param signerPubkey signer publickey used in heimdall node.
function stakeFor(
address user,
uint256 amount,
uint256 heimdallFee,
bool acceptDelegation,
bytes memory signerPubkey
) external;
/// @notice Restake Matics for a validator on polygon stake manager.
/// @param validatorId validator id.
/// @param amount amount to stake.
/// @param stakeRewards restake rewards.
function restake(
uint256 validatorId,
uint256 amount,
bool stakeRewards
) external;
/// @notice Request unstake a validator.
/// @param validatorId validator id.
function unstake(uint256 validatorId) external;
/// @notice Increase the heimdall fees.
/// @param user user that own the validator in our case the validator contract.
/// @param heimdallFee heimdall fees.
function topUpForFee(address user, uint256 heimdallFee) external;
/// @notice Get the validator id using the user address.
/// @param user user that own the validator in our case the validator contract.
/// @return return the validator id
function getValidatorId(address user) external view returns (uint256);
/// @notice get the validator contract used for delegation.
/// @param validatorId validator id.
/// @return return the address of the validator contract.
function getValidatorContract(uint256 validatorId)
external
view
returns (address);
/// @notice Withdraw accumulated rewards
/// @param validatorId validator id.
function withdrawRewards(uint256 validatorId) external;
/// @notice Get validator total staked.
/// @param validatorId validator id.
function validatorStake(uint256 validatorId)
external
view
returns (uint256);
/// @notice Allows to unstake the staked tokens on the stakeManager.
/// @param validatorId validator id.
function unstakeClaim(uint256 validatorId) external;
/// @notice Allows to update the signer pubkey
/// @param _validatorId validator id
/// @param _signerPubkey update signer public key
function updateSigner(uint256 _validatorId, bytes memory _signerPubkey)
external;
/// @notice Allows to claim the heimdall fees.
/// @param _accumFeeAmount accumulated fees amount
/// @param _index index
/// @param _proof proof
function claimFee(
uint256 _accumFeeAmount,
uint256 _index,
bytes memory _proof
) external;
/// @notice Allows to update the commision rate of a validator
/// @param _validatorId operator id
/// @param _newCommissionRate commission rate
function updateCommissionRate(
uint256 _validatorId,
uint256 _newCommissionRate
) external;
/// @notice Allows to unjail a validator.
/// @param _validatorId id of the validator that is to be unjailed
function unjail(uint256 _validatorId) external;
/// @notice Returns a withdrawal delay.
function withdrawalDelay() external view returns (uint256);
/// @notice Transfers amount from delegator
function delegationDeposit(
uint256 validatorId,
uint256 amount,
address delegator
) external returns (bool);
function epoch() external view returns (uint256);
enum Status {
Inactive,
Active,
Locked,
Unstaked
}
struct Validator {
uint256 amount;
uint256 reward;
uint256 activationEpoch;
uint256 deactivationEpoch;
uint256 jailTime;
address signer;
address contractAddress;
Status status;
uint256 commissionRate;
uint256 lastCommissionUpdate;
uint256 delegatorsReward;
uint256 delegatedAmount;
uint256 initialRewardPerStake;
}
function validators(uint256 _index)
external
view
returns (Validator memory);
/// @notice Returns the address of the nft contract
function NFTContract() external view returns (address);
/// @notice Returns the validator accumulated rewards on stake manager.
function validatorReward(uint256 validatorId)
external
view
returns (uint256);
}
// 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 (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 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @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-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
interface IValidatorShare {
struct DelegatorUnbond {
uint256 shares;
uint256 withdrawEpoch;
}
function unbondNonces(address _address) external view returns (uint256);
function activeAmount() external view returns (uint256);
function validatorId() external view returns (uint256);
function withdrawExchangeRate() external view returns (uint256);
function withdrawRewards() external;
function unstakeClaimTokens() external;
function minAmount() external view returns (uint256);
function getLiquidRewards(address user) external view returns (uint256);
function delegation() external view returns (bool);
function updateDelegation(bool _delegation) external;
function buyVoucher(uint256 _amount, uint256 _minSharesToMint)
external
returns (uint256);
function sellVoucher_new(uint256 claimAmount, uint256 maximumSharesToBurn)
external;
function unstakeClaimTokens_new(uint256 unbondNonce) external;
function unbonds_new(address _address, uint256 _unbondNonce)
external
view
returns (DelegatorUnbond memory);
function getTotalStake(address user)
external
view
returns (uint256, uint256);
function owner() external view returns (address);
function restake() external returns (uint256, uint256);
function unlock() external;
function lock() external;
function drain(
address token,
address payable destination,
uint256 amount
) external;
function slash(uint256 _amount) external;
function migrateOut(address user, uint256 amount) external;
function migrateIn(address user, uint256 amount) external;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
/// @title PoLidoNFT interface.
/// @author 2021 ShardLabs
interface IPoLidoNFT is IERC721Upgradeable {
function mint(address _to) external returns (uint256);
function burn(uint256 _tokenId) external;
function isApprovedOrOwner(address _spender, uint256 _tokenId)
external
view
returns (bool);
function setStMATIC(address _stMATIC) external;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
interface IFxStateRootTunnel {
function latestData() external view returns (bytes memory);
function setFxChildTunnel(address _fxChildTunnel) external;
function sendMessageToChild(bytes memory message) external;
function setStMATIC(address _stMATIC) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
} | @notice Allows to set the contract version. @param _version contract version | function setVersion(string memory _version)
external
override
userHasRole(DEFAULT_ADMIN_ROLE)
{
version = _version;
}
| 6,084,906 | [
1,
19132,
358,
444,
326,
6835,
1177,
18,
225,
389,
1589,
6835,
1177,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16770,
12,
1080,
3778,
389,
1589,
13,
203,
3639,
3903,
203,
3639,
3849,
203,
3639,
729,
5582,
2996,
12,
5280,
67,
15468,
67,
16256,
13,
203,
565,
288,
203,
3639,
1177,
273,
389,
1589,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity >0.4.24 <0.6.0;
/**
* Integers Library
*
* In summary this is a simple library of integer functions which allow a simple
* conversion to and from strings
*
* @author James Lockhart <[email protected]>
* @dev Fixed by Ryo Komiyama <https://github.com/ryokomy>
*/
library Integers {
/**
* To String
*
* Converts an unsigned integer to the ASCII string equivalent value
*
* @param _base The unsigned integer to be converted to a string
* @return string The resulting ASCII string value
*/
function toString(uint256 _base)
internal
pure
returns (string memory)
{
bytes memory _tmp = new bytes(32);
uint256 _tmpBase = _base;
uint256 i;
for(i = 0; _tmpBase > 0; i++) {
_tmp[i] = bytes1((uint8(_tmpBase % 10) + 48));
_tmpBase /= 10;
}
bytes memory _real = new bytes(i--);
for(uint256 j = 0; j < _real.length; j++) {
_real[j] = _tmp[i--];
}
return string(_real);
}
} | * To String Converts an unsigned integer to the ASCII string equivalent value @param _base The unsigned integer to be converted to a string @return string The resulting ASCII string value/ | {
bytes memory _tmp = new bytes(32);
uint256 _tmpBase = _base;
uint256 i;
for(i = 0; _tmpBase > 0; i++) {
_tmp[i] = bytes1((uint8(_tmpBase % 10) + 48));
_tmpBase /= 10;
}
bytes memory _real = new bytes(i--);
for(uint256 j = 0; j < _real.length; j++) {
_real[j] = _tmp[i--];
}
return string(_real);
}
| 13,094,812 | [
1,
774,
514,
20377,
392,
9088,
3571,
358,
326,
11768,
533,
7680,
460,
225,
389,
1969,
1021,
9088,
3571,
358,
506,
5970,
358,
279,
533,
327,
533,
1021,
8156,
11768,
533,
460,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
288,
203,
3639,
1731,
3778,
389,
5645,
273,
394,
1731,
12,
1578,
1769,
203,
3639,
2254,
5034,
389,
5645,
2171,
273,
389,
1969,
31,
203,
3639,
2254,
5034,
277,
31,
203,
3639,
364,
12,
77,
273,
374,
31,
389,
5645,
2171,
405,
374,
31,
277,
27245,
288,
203,
5411,
389,
5645,
63,
77,
65,
273,
1731,
21,
12443,
11890,
28,
24899,
5645,
2171,
738,
1728,
13,
397,
9934,
10019,
203,
5411,
389,
5645,
2171,
9531,
1728,
31,
203,
3639,
289,
203,
3639,
1731,
3778,
389,
7688,
273,
394,
1731,
12,
77,
413,
1769,
203,
3639,
364,
12,
11890,
5034,
525,
273,
374,
31,
525,
411,
389,
7688,
18,
2469,
31,
525,
27245,
288,
203,
5411,
389,
7688,
63,
78,
65,
273,
389,
5645,
63,
77,
413,
15533,
203,
3639,
289,
203,
3639,
327,
533,
24899,
7688,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x34790dfca967661FDb429bE4C98c78a224E6a12d/sources/CR7.sol | @notice Sets the fees for sells @param _marketingFee The fee for the marketing wallet @param _liquidityFee The fee for the liquidity pool @param _devFee The fee for the dev wallet | function updateSellFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
totalFeesSell = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
| 9,147,556 | [
1,
2785,
326,
1656,
281,
364,
357,
3251,
225,
389,
3355,
21747,
14667,
1021,
14036,
364,
326,
13667,
310,
9230,
225,
389,
549,
372,
24237,
14667,
1021,
14036,
364,
326,
4501,
372,
24237,
2845,
225,
389,
5206,
14667,
1021,
14036,
364,
326,
4461,
9230,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1089,
55,
1165,
2954,
281,
12,
203,
3639,
2254,
5034,
389,
3355,
21747,
14667,
16,
203,
3639,
2254,
5034,
389,
549,
372,
24237,
14667,
16,
203,
3639,
2254,
5034,
389,
5206,
14667,
203,
565,
262,
3903,
1338,
5541,
288,
203,
3639,
357,
80,
3882,
21747,
14667,
273,
389,
3355,
21747,
14667,
31,
203,
3639,
357,
80,
48,
18988,
24237,
14667,
273,
389,
549,
372,
24237,
14667,
31,
203,
3639,
357,
80,
8870,
14667,
273,
389,
5206,
14667,
31,
203,
3639,
2078,
2954,
281,
55,
1165,
273,
357,
80,
3882,
21747,
14667,
397,
357,
80,
48,
18988,
24237,
14667,
397,
357,
80,
8870,
14667,
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
]
|
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.6.12;
import "./Interfaces/LiquidityMathModelInterface.sol";
import "./MToken.sol";
import "./Utils/ErrorReporter.sol";
import "./Utils/ExponentialNoError.sol";
import "./Utils/AssetHelpers.sol";
import "./Moartroller.sol";
import "./SimplePriceOracle.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract LiquidityMathModelV1 is LiquidityMathModelInterface, LiquidityMathModelErrorReporter, ExponentialNoError, Ownable, AssetHelpers {
/**
* @notice get the maximum asset value that can be still optimized.
* @notice if protectionId is supplied, the maxOptimizableValue is increased by the protection lock value'
* which is helpful to recalculate how much of this protection can be optimized again
*/
function getMaxOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) external override view returns (uint){
uint returnValue;
uint hypotheticalOptimizableValue = getHypotheticalOptimizableValue(arguments);
uint totalProtectionLockedValue;
(totalProtectionLockedValue, ) = getTotalProtectionLockedValue(arguments);
if(hypotheticalOptimizableValue <= totalProtectionLockedValue){
returnValue = 0;
}
else{
returnValue = sub_(hypotheticalOptimizableValue, totalProtectionLockedValue);
}
return returnValue;
}
/**
* @notice get the maximum value of an asset that can be optimized by protection for the given user
* @dev optimizable = asset value * MPC
* @return the hypothetical optimizable value
* TODO: replace hardcoded 1e18 values
*/
function getHypotheticalOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint) {
uint assetValue = div_(
mul_(
div_(
mul_(
arguments.asset.balanceOf(arguments.account),
arguments.asset.exchangeRateStored()
),
1e18
),
arguments.oracle.getUnderlyingPrice(arguments.asset)
),
getAssetDecimalsMantissa(arguments.asset.getUnderlying())
);
uint256 hypotheticalOptimizableValue = div_(
mul_(
assetValue,
arguments.asset.maxProtectionComposition()
),
arguments.asset.maxProtectionCompositionMantissa()
);
return hypotheticalOptimizableValue;
}
/**
* @dev gets all locked protections values with mark to market value. Used by Moartroller.
*/
function getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint, uint) {
uint _lockedValue = 0;
uint _markToMarket = 0;
uint _protectionCount = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(arguments.account, arguments.asset.underlying());
for (uint j = 0; j < _protectionCount; j++) {
uint protectionId = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrency(arguments.account, arguments.asset.underlying(), j);
bool protectionIsAlive = arguments.cprotection.isProtectionAlive(protectionId);
if(protectionIsAlive){
_lockedValue = add_(_lockedValue, arguments.cprotection.getUnderlyingProtectionLockedValue(protectionId));
uint assetSpotPrice = arguments.oracle.getUnderlyingPrice(arguments.asset);
uint protectionStrikePrice = arguments.cprotection.getUnderlyingStrikePrice(protectionId);
if( assetSpotPrice > protectionStrikePrice) {
_markToMarket = _markToMarket + div_(
mul_(
div_(
mul_(
assetSpotPrice - protectionStrikePrice,
arguments.cprotection.getUnderlyingProtectionLockedAmount(protectionId)
),
getAssetDecimalsMantissa(arguments.asset.underlying())
),
arguments.collateralFactorMantissa
),
1e18
);
}
}
}
return (_lockedValue , _markToMarket);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.6.12;
import "../MToken.sol";
import "../MProtection.sol";
import "../Interfaces/PriceOracle.sol";
interface LiquidityMathModelInterface {
struct LiquidityMathArgumentsSet {
MToken asset;
address account;
uint collateralFactorMantissa;
MProtection cprotection;
PriceOracle oracle;
}
function getMaxOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns (uint);
function getHypotheticalOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint);
function getTotalProtectionLockedValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint, uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Utils/ErrorReporter.sol";
import "./Utils/Exponential.sol";
import "./Interfaces/EIP20Interface.sol";
import "./MTokenStorage.sol";
import "./Interfaces/MTokenInterface.sol";
import "./Interfaces/MProxyInterface.sol";
import "./Moartroller.sol";
import "./AbstractInterestRateModel.sol";
/**
* @title MOAR's MToken Contract
* @notice Abstract base for MTokens
* @author MOAR
*/
abstract contract MToken is MTokenInterface, Exponential, TokenErrorReporter, MTokenStorage {
/**
* @notice Indicator that this is a MToken contract (for inspection)
*/
bool public constant isMToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address MTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when moartroller is changed
*/
event NewMoartroller(Moartroller oldMoartroller, Moartroller newMoartroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModelInterface oldInterestRateModel, InterestRateModelInterface newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/**
* @notice Max protection composition value updated event
*/
event MpcUpdated(uint newValue);
/**
* @notice Initialize the money market
* @param moartroller_ The address of the Moartroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function init(Moartroller moartroller_,
AbstractInterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "not_admin");
require(accrualBlockNumber == 0 && borrowIndex == 0, "already_init");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "too_low");
// Set the moartroller
uint err = _setMoartroller(moartroller_);
require(err == uint(Error.NO_ERROR), "setting moartroller failed");
// Initialize block number and borrow index (block number mocks depend on moartroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting IRM failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
maxProtectionComposition = 5000;
maxProtectionCompositionMantissa = 1e4;
reserveFactorMaxMantissa = 1e18;
borrowRateMaxMantissa = 0.0005e16;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = moartroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.TRANSFER_MOARTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srmTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srmTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srmTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
// unused function
// moartroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external virtual override nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external virtual override nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external virtual override returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external virtual override view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external virtual override view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external virtual override returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance_calculation_failed");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by moartroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external virtual override view returns (uint, uint, uint, uint) {
uint mTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), mTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this mToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external virtual override view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this mToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external virtual override view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external virtual override nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external virtual override nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public virtual view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public virtual nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the MToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public virtual view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the MToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this mToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external virtual override view returns (uint) {
return getCashPrior();
}
function getRealBorrowIndex() public view returns (uint) {
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high");
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calc block delta");
Exp memory simpleInterestFactor;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
require(mathErr == MathError.NO_ERROR, "could not calc simpleInterestFactor");
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
require(mathErr == MathError.NO_ERROR, "could not calc borrowIndex");
return borrowIndexNew;
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public virtual returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calc block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
AccrueInterestTempStorage memory temp;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.totalBorrowsNew) = addUInt(temp.interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.reservesAdded) = mulScalarTruncate(Exp({mantissa: reserveFactorMantissa}), temp.interestAccumulated);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.splitedReserves_2) = mulScalarTruncate(Exp({mantissa: reserveSplitFactorMantissa}), temp.reservesAdded);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.splitedReserves_1) = subUInt(temp.reservesAdded, temp.splitedReserves_2);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.totalReservesNew) = addUInt(temp.splitedReserves_1, reservesPrior);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = temp.borrowIndexNew;
totalBorrows = temp.totalBorrowsNew;
totalReserves = temp.totalReservesNew;
if(temp.splitedReserves_2 > 0){
address mProxy = moartroller.mProxy();
EIP20Interface(underlying).approve(mProxy, temp.splitedReserves_2);
MProxyInterface(mProxy).proxySplitReserves(underlying, temp.splitedReserves_2);
}
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, temp.interestAccumulated, temp.borrowIndexNew, temp.totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives mTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives mTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = moartroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.MINT_MOARTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the mToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of mTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_E");
/*
* We calculate the new total supply of mTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_E");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_E");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
// unused function
// moartroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems mTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of mTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems mTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming mTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems mTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of mTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming mTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "redeemFresh_missing_zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = moartroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REDEEM_MOARTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/* Fail if user tries to redeem more than he has locked with c-op*/
// TODO: update error codes
uint newTokensAmount = div_(mul_(vars.accountTokensNew, vars.exchangeRateMantissa), 1e18);
if (newTokensAmount < moartroller.getUserLockedAmount(this, redeemer)) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
moartroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
function borrowForInternal(address payable borrower, uint borrowAmount) internal nonReentrant returns (uint) {
require(moartroller.isPrivilegedAddress(msg.sender), "permission_missing");
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(borrower, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = moartroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.BORROW_MOARTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
//unused function
// moartroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = moartroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REPAY_BORROW_MOARTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
/* If the borrow is repaid by another user -1 cannot be used to prevent borrow front-running */
if (repayAmount == uint(-1)) {
require(tx.origin == borrower, "specify a precise amount");
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
// unused function
// moartroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this mToken to be liquidated
* @param mTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, MToken mTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = mTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, mTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this mToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param mTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, MToken mTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = moartroller.liquidateBorrowAllowed(address(this), address(mTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_MOARTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify mTokenCollateral market's block number equals current block number */
if (mTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = moartroller.liquidateCalculateSeizeUserTokens(address(this), address(mTokenCollateral), actualRepayAmount, borrower);
require(amountSeizeError == uint(Error.NO_ERROR), "CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(mTokenCollateral.balanceOf(borrower) >= seizeTokens, "TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(mTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = mTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(mTokenCollateral), seizeTokens);
/* We call the defense hook */
// unused function
// moartroller.liquidateBorrowVerify(address(this), address(mTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another mToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed mToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of mTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external virtual override nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another MToken.
* Its absolutely critical to use msg.sender as the seizer mToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed mToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of mTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = moartroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_MOARTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
// unused function
// moartroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external virtual override returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external virtual override returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new moartroller for the market
* @dev Admin function to set a new moartroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setMoartroller(Moartroller newMoartroller) public virtual returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_MOARTROLLER_OWNER_CHECK);
}
Moartroller oldMoartroller = moartroller;
// Ensure invoke moartroller.isMoartroller() returns true
require(newMoartroller.isMoartroller(), "not_moartroller");
// Set market's moartroller to newMoartroller
moartroller = newMoartroller;
// Emit NewMoartroller(oldMoartroller, newMoartroller)
emit NewMoartroller(oldMoartroller, newMoartroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external virtual override nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
function _setReserveSplitFactor(uint newReserveSplitFactorMantissa) external nonReentrant returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
reserveSplitFactorMantissa = newReserveSplitFactorMantissa;
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external virtual override nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(AbstractInterestRateModel newInterestRateModel) public virtual returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(AbstractInterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModelInterface oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "not_interest_model");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets new value for max protection composition parameter
* @param newMPC New value of MPC
* @return uint 0=success, otherwise a failure
*/
function _setMaxProtectionComposition(uint256 newMPC) external returns(uint){
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
maxProtectionComposition = newMPC;
emit MpcUpdated(newMPC);
return uint(Error.NO_ERROR);
}
/**
* @notice Returns address of underlying token
* @return address of underlying token
*/
function getUnderlying() external override view returns(address){
return underlying;
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal virtual view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal virtual returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal virtual;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
contract MoartrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
MOARTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SUPPORT_PROTECTION_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
MOARTROLLER_REJECTION,
MOARTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_MOARTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_MOARTROLLER_REJECTION,
LIQUIDATE_MOARTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_MOARTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_MOARTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_MOARTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_MOARTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_MOARTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_MOARTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract LiquidityMathModelErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
PRICE_ERROR,
SNAPSHOT_ERROR
}
enum FailureInfo {
ORACLE_PRICE_CHECK_FAILED
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/**
* @title Exponential module for storing fixed-precision decimals
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract ExponentialNoError {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "../Interfaces/EIP20Interface.sol";
contract AssetHelpers {
/**
* @dev return asset decimals mantissa. Returns 1e18 if ETH
*/
function getAssetDecimalsMantissa(address assetAddress) public view returns (uint256){
uint assetDecimals = 1e18;
if (assetAddress != address(0)) {
EIP20Interface token = EIP20Interface(assetAddress);
assetDecimals = 10 ** uint256(token.decimals());
}
return assetDecimals;
}
}
// SPDX-License-Identifier: BSD-3-Clause
// Thanks to Compound for their foundational work in DeFi and open-sourcing their code from which we build upon.
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
// import "hardhat/console.sol";
import "./MToken.sol";
import "./Utils/ErrorReporter.sol";
import "./Utils/ExponentialNoError.sol";
import "./Interfaces/PriceOracle.sol";
import "./Interfaces/MoartrollerInterface.sol";
import "./Interfaces/Versionable.sol";
import "./Interfaces/MProxyInterface.sol";
import "./MoartrollerStorage.sol";
import "./Governance/UnionGovernanceToken.sol";
import "./MProtection.sol";
import "./Interfaces/LiquidityMathModelInterface.sol";
import "./LiquidityMathModelV1.sol";
import "./Utils/SafeEIP20.sol";
import "./Interfaces/EIP20Interface.sol";
import "./Interfaces/LiquidationModelInterface.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* @title MOAR's Moartroller Contract
* @author MOAR
*/
contract Moartroller is MoartrollerV6Storage, MoartrollerInterface, MoartrollerErrorReporter, ExponentialNoError, Versionable, Initializable {
using SafeEIP20 for EIP20Interface;
/// @notice Indicator that this is a Moartroller contract (for inspection)
bool public constant isMoartroller = true;
/// @notice Emitted when an admin supports a market
event MarketListed(MToken mToken);
/// @notice Emitted when an account enters a market
event MarketEntered(MToken mToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(MToken mToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(MToken mToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when protection is changed
event NewCProtection(MProtection oldCProtection, MProtection newCProtection);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPausedMToken(MToken mToken, string action, bool pauseState);
/// @notice Emitted when a new MOAR speed is calculated for a market
event MoarSpeedUpdated(MToken indexed mToken, uint newSpeed);
/// @notice Emitted when a new MOAR speed is set for a contributor
event ContributorMoarSpeedUpdated(address indexed contributor, uint newSpeed);
/// @notice Emitted when MOAR is distributed to a supplier
event DistributedSupplierMoar(MToken indexed mToken, address indexed supplier, uint moarDelta, uint moarSupplyIndex);
/// @notice Emitted when MOAR is distributed to a borrower
event DistributedBorrowerMoar(MToken indexed mToken, address indexed borrower, uint moarDelta, uint moarBorrowIndex);
/// @notice Emitted when borrow cap for a mToken is changed
event NewBorrowCap(MToken indexed mToken, uint newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
/// @notice Emitted when MOAR is granted by admin
event MoarGranted(address recipient, uint amount);
event NewLiquidityMathModel(address oldLiquidityMathModel, address newLiquidityMathModel);
event NewLiquidationModel(address oldLiquidationModel, address newLiquidationModel);
/// @notice The initial MOAR index for a market
uint224 public constant moarInitialIndex = 1e36;
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
// Custom initializer
function initialize(LiquidityMathModelInterface mathModel, LiquidationModelInterface lqdModel) public initializer {
admin = msg.sender;
liquidityMathModel = mathModel;
liquidationModel = lqdModel;
rewardClaimEnabled = false;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (MToken[] memory) {
MToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param mToken The mToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, MToken mToken) external view returns (bool) {
return markets[address(mToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param mTokens The list of addresses of the mToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory mTokens) public override returns (uint[] memory) {
uint len = mTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
MToken mToken = MToken(mTokens[i]);
results[i] = uint(addToMarketInternal(mToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param mToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(MToken mToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(mToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(mToken);
emit MarketEntered(mToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param mTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address mTokenAddress) external override returns (uint) {
MToken mToken = MToken(mTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the mToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = mToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(mTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(mToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set mToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete mToken from the account’s list of assets */
// load into memory for faster iteration
MToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == mToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
MToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.pop();
emit MarketExited(mToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param mToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address mToken, address minter, uint mintAmount) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[mToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateMoarSupplyIndex(mToken);
distributeSupplierMoar(mToken, minter);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param mToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of mTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external override returns (uint) {
uint allowed = redeemAllowedInternal(mToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateMoarSupplyIndex(mToken);
distributeSupplierMoar(mToken, redeemer);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address mToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[mToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, MToken(mToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param mToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external override {
// Shh - currently unused
mToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param mToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address mToken, address borrower, uint borrowAmount) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[mToken], "borrow is paused");
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[mToken].accountMembership[borrower]) {
// only mTokens may call borrowAllowed if borrower not in market
require(msg.sender == mToken, "sender must be mToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(MToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[mToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(MToken(mToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[mToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = MToken(mToken).totalBorrows();
uint nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, MToken(mToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()});
updateMoarBorrowIndex(mToken, borrowIndex);
distributeBorrowerMoar(mToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param mToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address mToken,
address payer,
address borrower,
uint repayAmount) external override returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()});
updateMoarBorrowIndex(mToken, borrowIndex);
distributeBorrowerMoar(mToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address mTokenBorrowed,
address mTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external override returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[mTokenBorrowed].isListed || !markets[mTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = MToken(mTokenBorrowed).borrowBalanceStored(borrower);
uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address mTokenCollateral,
address mTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[mTokenCollateral].isListed || !markets[mTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (MToken(mTokenCollateral).moartroller() != MToken(mTokenBorrowed).moartroller()) {
return uint(Error.MOARTROLLER_MISMATCH);
}
// Keep the flywheel moving
updateMoarSupplyIndex(mTokenCollateral);
distributeSupplierMoar(mTokenCollateral, borrower);
distributeSupplierMoar(mTokenCollateral, liquidator);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param mToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of mTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address mToken, address src, address dst, uint transferTokens) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(mToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateMoarSupplyIndex(mToken);
distributeSupplierMoar(mToken, src);
distributeSupplierMoar(mToken, dst);
return uint(Error.NO_ERROR);
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param mTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address mTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(mTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param mTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral mToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
MToken mTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
// For each asset the account is in
MToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
MToken asset = assets[i];
address _account = account;
// Read the balances and exchange rate from the mToken
(oErr, vars.mTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(_account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = mul_(Exp({mantissa: vars.oraclePriceMantissa}), 10**uint256(18 - EIP20Interface(asset.getUnderlying()).decimals()));
// Pre-compute a conversion factor from tokens -> dai (normalized price value)
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
// sumCollateral += tokensToDenom * mTokenBalance
vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.mTokenBalance, vars.sumCollateral);
// Protection value calculation sumCollateral += protectionValueLocked
// Mark to market value calculation sumCollateral += markToMarketValue
uint protectionValueLocked;
uint markToMarketValue;
(protectionValueLocked, markToMarketValue) = liquidityMathModel.getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet(asset, _account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle));
if (vars.sumCollateral < mul_( protectionValueLocked, vars.collateralFactor)) {
vars.sumCollateral = 0;
} else {
vars.sumCollateral = sub_(vars.sumCollateral, mul_( protectionValueLocked, vars.collateralFactor));
}
vars.sumCollateral = add_(vars.sumCollateral, protectionValueLocked);
vars.sumCollateral = add_(vars.sumCollateral, markToMarketValue);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
// Calculate effects of interacting with mTokenModify
if (asset == mTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
_account = account;
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Returns the value of possible optimization left for asset
* @param asset The MToken address
* @param account The owner of asset
* @return The value of possible optimization
*/
function getMaxOptimizableValue(MToken asset, address account) public view returns(uint){
return liquidityMathModel.getMaxOptimizableValue(
LiquidityMathModelInterface.LiquidityMathArgumentsSet(
asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle
)
);
}
/**
* @notice Returns the value of hypothetical optimization (ignoring existing optimization used) for asset
* @param asset The MToken address
* @param account The owner of asset
* @return The amount of hypothetical optimization
*/
function getHypotheticalOptimizableValue(MToken asset, address account) public view returns(uint){
return liquidityMathModel.getHypotheticalOptimizableValue(
LiquidityMathModelInterface.LiquidityMathArgumentsSet(
asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle
)
);
}
function liquidateCalculateSeizeUserTokens(address mTokenBorrowed, address mTokenCollateral, uint actualRepayAmount, address account) external override view returns (uint, uint) {
return LiquidationModelInterface(liquidationModel).liquidateCalculateSeizeUserTokens(
LiquidationModelInterface.LiquidateCalculateSeizeUserTokensArgumentsSet(
oracle,
this,
mTokenBorrowed,
mTokenCollateral,
actualRepayAmount,
account,
liquidationIncentiveMantissa
)
);
}
/**
* @notice Returns the amount of a specific asset that is locked under all c-ops
* @param asset The MToken address
* @param account The owner of asset
* @return The amount of asset locked under c-ops
*/
function getUserLockedAmount(MToken asset, address account) public override view returns(uint) {
uint protectionLockedAmount;
address currency = asset.underlying();
uint256 numOfProtections = cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(account, currency);
for (uint i = 0; i < numOfProtections; i++) {
uint cProtectionId = cprotection.getUserUnderlyingProtectionTokenIdByCurrency(account, currency, i);
if(cprotection.isProtectionAlive(cProtectionId)){
protectionLockedAmount = protectionLockedAmount + cprotection.getUnderlyingProtectionLockedAmount(cProtectionId);
}
}
return protectionLockedAmount;
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the moartroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the moartroller
PriceOracle oldOracle = oracle;
// Set moartroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new CProtection that is allowed to use as a collateral optimisation
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setProtection(address newCProtection) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
MProtection oldCProtection = cprotection;
cprotection = MProtection(newCProtection);
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewCProtection(oldCProtection, cprotection);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param mToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(MToken mToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(mToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
// TODO: this check is temporary switched off. we can make exception for UNN later
// Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
//
//
// Check collateral factor <= 0.9
// Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
// if (lessThanExp(highLimit, newCollateralFactorExp)) {
// return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
// }
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(mToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(mToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
function _setRewardClaimEnabled(bool status) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
rewardClaimEnabled = status;
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param mToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(MToken mToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(mToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
mToken.isMToken(); // Sanity check to make sure its really a MToken
// Note that isMoared is not in active use anymore
markets[address(mToken)] = Market({isListed: true, isMoared: false, collateralFactorMantissa: 0});
tokenAddressToMToken[address(mToken.underlying())] = mToken;
_addMarketInternal(address(mToken));
emit MarketListed(mToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address mToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != MToken(mToken), "market already added");
}
allMarkets.push(MToken(mToken));
}
/**
* @notice Set the given borrow caps for the given mToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param mTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(MToken[] calldata mTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps");
uint numMarkets = mTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for(uint i = 0; i < numMarkets; i++) {
borrowCaps[address(mTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(mTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external {
require(msg.sender == admin, "only admin can set borrow cap guardian");
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(MToken mToken, bool state) public returns (bool) {
require(markets[address(mToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(mToken)] = state;
emit ActionPausedMToken(mToken, "Mint", state);
return state;
}
function _setBorrowPaused(MToken mToken, bool state) public returns (bool) {
require(markets[address(mToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(mToken)] = state;
emit ActionPausedMToken(mToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == moartrollerImplementation;
}
/*** MOAR Distribution ***/
/**
* @notice Set MOAR speed for a single market
* @param mToken The market whose MOAR speed to update
* @param moarSpeed New MOAR speed for market
*/
function setMoarSpeedInternal(MToken mToken, uint moarSpeed) internal {
uint currentMoarSpeed = moarSpeeds[address(mToken)];
if (currentMoarSpeed != 0) {
// note that MOAR speed could be set to 0 to halt liquidity rewards for a market
Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()});
updateMoarSupplyIndex(address(mToken));
updateMoarBorrowIndex(address(mToken), borrowIndex);
} else if (moarSpeed != 0) {
// Add the MOAR market
Market storage market = markets[address(mToken)];
require(market.isListed == true, "MOAR market is not listed");
if (moarSupplyState[address(mToken)].index == 0 && moarSupplyState[address(mToken)].block == 0) {
moarSupplyState[address(mToken)] = MoarMarketState({
index: moarInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
if (moarBorrowState[address(mToken)].index == 0 && moarBorrowState[address(mToken)].block == 0) {
moarBorrowState[address(mToken)] = MoarMarketState({
index: moarInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
}
if (currentMoarSpeed != moarSpeed) {
moarSpeeds[address(mToken)] = moarSpeed;
emit MoarSpeedUpdated(mToken, moarSpeed);
}
}
/**
* @notice Accrue MOAR to the market by updating the supply index
* @param mToken The market whose supply index to update
*/
function updateMoarSupplyIndex(address mToken) internal {
MoarMarketState storage supplyState = moarSupplyState[mToken];
uint supplySpeed = moarSpeeds[mToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));
if (deltaBlocks > 0 && supplySpeed > 0) {
uint supplyTokens = MToken(mToken).totalSupply();
uint moarAccrued = mul_(deltaBlocks, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(moarAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: supplyState.index}), ratio);
moarSupplyState[mToken] = MoarMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Accrue MOAR to the market by updating the borrow index
* @param mToken The market whose borrow index to update
*/
function updateMoarBorrowIndex(address mToken, Exp memory marketBorrowIndex) internal {
MoarMarketState storage borrowState = moarBorrowState[mToken];
uint borrowSpeed = moarSpeeds[mToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(MToken(mToken).totalBorrows(), marketBorrowIndex);
uint moarAccrued = mul_(deltaBlocks, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(moarAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: borrowState.index}), ratio);
moarBorrowState[mToken] = MoarMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Calculate MOAR accrued by a supplier and possibly transfer it to them
* @param mToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute MOAR to
*/
function distributeSupplierMoar(address mToken, address supplier) internal {
MoarMarketState storage supplyState = moarSupplyState[mToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: moarSupplierIndex[mToken][supplier]});
moarSupplierIndex[mToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = moarInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = MToken(mToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(moarAccrued[supplier], supplierDelta);
moarAccrued[supplier] = supplierAccrued;
emit DistributedSupplierMoar(MToken(mToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate MOAR accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param mToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute MOAR to
*/
function distributeBorrowerMoar(address mToken, address borrower, Exp memory marketBorrowIndex) internal {
MoarMarketState storage borrowState = moarBorrowState[mToken];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: moarBorrowerIndex[mToken][borrower]});
moarBorrowerIndex[mToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(MToken(mToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint borrowerAccrued = add_(moarAccrued[borrower], borrowerDelta);
moarAccrued[borrower] = borrowerAccrued;
emit DistributedBorrowerMoar(MToken(mToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Calculate additional accrued MOAR for a contributor since last accrual
* @param contributor The address to calculate contributor rewards for
*/
function updateContributorRewards(address contributor) public {
uint moarSpeed = moarContributorSpeeds[contributor];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]);
if (deltaBlocks > 0 && moarSpeed > 0) {
uint newAccrued = mul_(deltaBlocks, moarSpeed);
uint contributorAccrued = add_(moarAccrued[contributor], newAccrued);
moarAccrued[contributor] = contributorAccrued;
lastContributorBlock[contributor] = blockNumber;
}
}
/**
* @notice Claim all the MOAR accrued by holder in all markets
* @param holder The address to claim MOAR for
*/
function claimMoarReward(address holder) public {
return claimMoar(holder, allMarkets);
}
/**
* @notice Claim all the MOAR accrued by holder in the specified markets
* @param holder The address to claim MOAR for
* @param mTokens The list of markets to claim MOAR in
*/
function claimMoar(address holder, MToken[] memory mTokens) public {
address[] memory holders = new address[](1);
holders[0] = holder;
claimMoar(holders, mTokens, true, true);
}
/**
* @notice Claim all MOAR accrued by the holders
* @param holders The addresses to claim MOAR for
* @param mTokens The list of markets to claim MOAR in
* @param borrowers Whether or not to claim MOAR earned by borrowing
* @param suppliers Whether or not to claim MOAR earned by supplying
*/
function claimMoar(address[] memory holders, MToken[] memory mTokens, bool borrowers, bool suppliers) public {
require(rewardClaimEnabled, "reward claim is disabled");
for (uint i = 0; i < mTokens.length; i++) {
MToken mToken = mTokens[i];
require(markets[address(mToken)].isListed, "market must be listed");
if (borrowers == true) {
Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()});
updateMoarBorrowIndex(address(mToken), borrowIndex);
for (uint j = 0; j < holders.length; j++) {
distributeBorrowerMoar(address(mToken), holders[j], borrowIndex);
moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]);
}
}
if (suppliers == true) {
updateMoarSupplyIndex(address(mToken));
for (uint j = 0; j < holders.length; j++) {
distributeSupplierMoar(address(mToken), holders[j]);
moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]);
}
}
}
}
/**
* @notice Transfer MOAR to the user
* @dev Note: If there is not enough MOAR, we do not perform the transfer all.
* @param user The address of the user to transfer MOAR to
* @param amount The amount of MOAR to (possibly) transfer
* @return The amount of MOAR which was NOT transferred to the user
*/
function grantMoarInternal(address user, uint amount) internal returns (uint) {
EIP20Interface moar = EIP20Interface(getMoarAddress());
uint moarRemaining = moar.balanceOf(address(this));
if (amount > 0 && amount <= moarRemaining) {
moar.approve(mProxy, amount);
MProxyInterface(mProxy).proxyClaimReward(getMoarAddress(), user, amount);
return 0;
}
return amount;
}
/*** MOAR Distribution Admin ***/
/**
* @notice Transfer MOAR to the recipient
* @dev Note: If there is not enough MOAR, we do not perform the transfer all.
* @param recipient The address of the recipient to transfer MOAR to
* @param amount The amount of MOAR to (possibly) transfer
*/
function _grantMoar(address recipient, uint amount) public {
require(adminOrInitializing(), "only admin can grant MOAR");
uint amountLeft = grantMoarInternal(recipient, amount);
require(amountLeft == 0, "insufficient MOAR for grant");
emit MoarGranted(recipient, amount);
}
/**
* @notice Set MOAR speed for a single market
* @param mToken The market whose MOAR speed to update
* @param moarSpeed New MOAR speed for market
*/
function _setMoarSpeed(MToken mToken, uint moarSpeed) public {
require(adminOrInitializing(), "only admin can set MOAR speed");
setMoarSpeedInternal(mToken, moarSpeed);
}
/**
* @notice Set MOAR speed for a single contributor
* @param contributor The contributor whose MOAR speed to update
* @param moarSpeed New MOAR speed for contributor
*/
function _setContributorMoarSpeed(address contributor, uint moarSpeed) public {
require(adminOrInitializing(), "only admin can set MOAR speed");
// note that MOAR speed could be set to 0 to halt liquidity rewards for a contributor
updateContributorRewards(contributor);
if (moarSpeed == 0) {
// release storage
delete lastContributorBlock[contributor];
} else {
lastContributorBlock[contributor] = getBlockNumber();
}
moarContributorSpeeds[contributor] = moarSpeed;
emit ContributorMoarSpeedUpdated(contributor, moarSpeed);
}
/**
* @notice Set liquidity math model implementation
* @param mathModel the math model implementation
*/
function _setLiquidityMathModel(LiquidityMathModelInterface mathModel) public {
require(msg.sender == admin, "only admin can set liquidity math model implementation");
LiquidityMathModelInterface oldLiquidityMathModel = liquidityMathModel;
liquidityMathModel = mathModel;
emit NewLiquidityMathModel(address(oldLiquidityMathModel), address(liquidityMathModel));
}
/**
* @notice Set liquidation model implementation
* @param newLiquidationModel the liquidation model implementation
*/
function _setLiquidationModel(LiquidationModelInterface newLiquidationModel) public {
require(msg.sender == admin, "only admin can set liquidation model implementation");
LiquidationModelInterface oldLiquidationModel = liquidationModel;
liquidationModel = newLiquidationModel;
emit NewLiquidationModel(address(oldLiquidationModel), address(liquidationModel));
}
function _setMoarToken(address moarTokenAddress) public {
require(msg.sender == admin, "only admin can set MOAR token address");
moarToken = moarTokenAddress;
}
function _setMProxy(address mProxyAddress) public {
require(msg.sender == admin, "only admin can set MProxy address");
mProxy = mProxyAddress;
}
/**
* @notice Add new privileged address
* @param privilegedAddress address to add
*/
function _addPrivilegedAddress(address privilegedAddress) public {
require(msg.sender == admin, "only admin can set liquidity math model implementation");
privilegedAddresses[privilegedAddress] = 1;
}
/**
* @notice Remove privileged address
* @param privilegedAddress address to remove
*/
function _removePrivilegedAddress(address privilegedAddress) public {
require(msg.sender == admin, "only admin can set liquidity math model implementation");
delete privilegedAddresses[privilegedAddress];
}
/**
* @notice Check if address if privileged
* @param privilegedAddress address to check
*/
function isPrivilegedAddress(address privilegedAddress) public view returns (bool) {
return privilegedAddresses[privilegedAddress] == 1;
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (MToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/**
* @notice Return the address of the MOAR token
* @return The address of MOAR
*/
function getMoarAddress() public view returns (address) {
return moarToken;
}
function getContractVersion() external override pure returns(string memory){
return "V1";
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Interfaces/PriceOracle.sol";
import "./CErc20.sol";
/**
* Temporary simple price feed
*/
contract SimplePriceOracle is PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
mapping(address => uint) prices;
event PricePosted(address asset, uint previousPriceMantissa, uint requestedPriceMantissa, uint newPriceMantissa);
function getUnderlyingPrice(MToken mToken) public override view returns (uint) {
if (compareStrings(mToken.symbol(), "mDAI")) {
return 1e18;
} else {
return prices[address(MErc20(address(mToken)).underlying())];
}
}
function setUnderlyingPrice(MToken mToken, uint underlyingPriceMantissa) public {
address asset = address(MErc20(address(mToken)).underlying());
emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa);
prices[asset] = underlyingPriceMantissa;
}
function setDirectPrice(address asset, uint price) public {
emit PricePosted(asset, prices[asset], price, price);
prices[asset] = price;
}
// v1 price oracle interface for use as backing of proxy
function assetPrices(address asset) external view returns (uint) {
return prices[asset];
}
function compareStrings(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "./Interfaces/CopMappingInterface.sol";
import "./Interfaces/Versionable.sol";
import "./Moartroller.sol";
import "./Utils/ExponentialNoError.sol";
import "./Utils/ErrorReporter.sol";
import "./Utils/AssetHelpers.sol";
import "./MToken.sol";
import "./Interfaces/EIP20Interface.sol";
import "./Utils/SafeEIP20.sol";
/**
* @title MOAR's MProtection Contract
* @notice Collateral optimization ERC-721 wrapper
* @author MOAR
*/
contract MProtection is ERC721Upgradeable, OwnableUpgradeable, ExponentialNoError, AssetHelpers, Versionable {
using Counters for Counters.Counter;
using EnumerableSet for EnumerableSet.UintSet;
/**
* @notice Event emitted when new MProtection token is minted
*/
event Mint(address minter, uint tokenId, uint underlyingTokenId, address asset, uint amount, uint strikePrice, uint expirationTime);
/**
* @notice Event emitted when MProtection token is redeemed
*/
event Redeem(address redeemer, uint tokenId, uint underlyingTokenId);
/**
* @notice Event emitted when MProtection token changes its locked value
*/
event LockValue(uint tokenId, uint underlyingTokenId, uint optimizationValue);
/**
* @notice Event emitted when maturity window parameter is changed
*/
event MaturityWindowUpdated(uint newMaturityWindow);
Counters.Counter private _tokenIds;
address private _copMappingAddress;
address private _moartrollerAddress;
mapping (uint256 => uint256) private _underlyingProtectionTokensMapping;
mapping (uint256 => uint256) private _underlyingProtectionLockedValue;
mapping (address => mapping (address => EnumerableSet.UintSet)) private _protectionCurrencyMapping;
uint256 public _maturityWindow;
struct ProtectionMappedData{
address pool;
address underlyingAsset;
uint256 amount;
uint256 strike;
uint256 premium;
uint256 lockedValue;
uint256 totalValue;
uint issueTime;
uint expirationTime;
bool isProtectionAlive;
}
/**
* @notice Constructor for MProtection contract
* @param copMappingAddress The address of data mapper for C-OP
* @param moartrollerAddress The address of the Moartroller
*/
function initialize(address copMappingAddress, address moartrollerAddress) public initializer {
__Ownable_init();
__ERC721_init("c-uUNN OC-Protection", "c-uUNN");
_copMappingAddress = copMappingAddress;
_moartrollerAddress = moartrollerAddress;
_setMaturityWindow(10800); // 3 hours default
}
/**
* @notice Returns C-OP mapping contract
*/
function copMapping() private view returns (CopMappingInterface){
return CopMappingInterface(_copMappingAddress);
}
/**
* @notice Mint new MProtection token
* @param underlyingTokenId Id of C-OP token that will be deposited
* @return ID of minted MProtection token
*/
function mint(uint256 underlyingTokenId) public returns (uint256)
{
return mintFor(underlyingTokenId, msg.sender);
}
/**
* @notice Mint new MProtection token for specified address
* @param underlyingTokenId Id of C-OP token that will be deposited
* @param receiver Address that will receive minted Mprotection token
* @return ID of minted MProtection token
*/
function mintFor(uint256 underlyingTokenId, address receiver) public returns (uint256)
{
CopMappingInterface copMappingInstance = copMapping();
ERC721Upgradeable(copMappingInstance.getTokenAddress()).transferFrom(msg.sender, address(this), underlyingTokenId);
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(receiver, newItemId);
addUProtectionIndexes(receiver, newItemId, underlyingTokenId);
emit Mint(
receiver,
newItemId,
underlyingTokenId,
copMappingInstance.getUnderlyingAsset(underlyingTokenId),
copMappingInstance.getUnderlyingAmount(underlyingTokenId),
copMappingInstance.getUnderlyingStrikePrice(underlyingTokenId),
copMappingInstance.getUnderlyingDeadline(underlyingTokenId)
);
return newItemId;
}
/**
* @notice Redeem C-OP token
* @param tokenId Id of MProtection token that will be withdrawn
* @return ID of redeemed C-OP token
*/
function redeem(uint256 tokenId) external returns (uint256) {
require(_isApprovedOrOwner(_msgSender(), tokenId), "cuUNN: caller is not owner nor approved");
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
ERC721Upgradeable(copMapping().getTokenAddress()).transferFrom(address(this), msg.sender, underlyingTokenId);
removeProtectionIndexes(tokenId);
_burn(tokenId);
emit Redeem(msg.sender, tokenId, underlyingTokenId);
return underlyingTokenId;
}
/**
* @notice Returns set of C-OP data
* @param tokenId Id of MProtection token
* @return ProtectionMappedData struct filled with C-OP data
*/
function getMappedProtectionData(uint256 tokenId) public view returns (ProtectionMappedData memory){
ProtectionMappedData memory data;
(address pool, uint256 amount, uint256 strike, uint256 premium, uint issueTime , uint expirationTime) = getProtectionData(tokenId);
data = ProtectionMappedData(pool, getUnderlyingAsset(tokenId), amount, strike, premium, getUnderlyingProtectionLockedValue(tokenId), getUnderlyingProtectionTotalValue(tokenId), issueTime, expirationTime, isProtectionAlive(tokenId));
return data;
}
/**
* @notice Returns underlying token ID
* @param tokenId Id of MProtection token
*/
function getUnderlyingProtectionTokenId(uint256 tokenId) public view returns (uint256){
return _underlyingProtectionTokensMapping[tokenId];
}
/**
* @notice Returns size of C-OPs filtered by asset address
* @param owner Address of wallet holding C-OPs
* @param currency Address of asset used to filter C-OPs
*/
function getUserUnderlyingProtectionTokenIdByCurrencySize(address owner, address currency) public view returns (uint256){
return _protectionCurrencyMapping[owner][currency].length();
}
/**
* @notice Returns list of C-OP IDs filtered by asset address
* @param owner Address of wallet holding C-OPs
* @param currency Address of asset used to filter C-OPs
*/
function getUserUnderlyingProtectionTokenIdByCurrency(address owner, address currency, uint256 index) public view returns (uint256){
return _protectionCurrencyMapping[owner][currency].at(index);
}
/**
* @notice Checks if address is owner of MProtection
* @param owner Address of potential owner to check
* @param tokenId ID of MProtection to check
*/
function isUserProtection(address owner, uint256 tokenId) public view returns(bool) {
if(Moartroller(_moartrollerAddress).isPrivilegedAddress(msg.sender)){
return true;
}
return owner == ownerOf(tokenId);
}
/**
* @notice Checks if MProtection is stil alive
* @param tokenId ID of MProtection to check
*/
function isProtectionAlive(uint256 tokenId) public view returns(bool) {
uint256 deadline = getUnderlyingDeadline(tokenId);
return (deadline - _maturityWindow) > now;
}
/**
* @notice Creates appropriate indexes for C-OP
* @param owner C-OP owner address
* @param tokenId ID of MProtection
* @param underlyingTokenId ID of C-OP
*/
function addUProtectionIndexes(address owner, uint256 tokenId, uint256 underlyingTokenId) private{
address currency = copMapping().getUnderlyingAsset(underlyingTokenId);
_underlyingProtectionTokensMapping[tokenId] = underlyingTokenId;
_protectionCurrencyMapping[owner][currency].add(tokenId);
}
/**
* @notice Remove indexes for C-OP
* @param tokenId ID of MProtection
*/
function removeProtectionIndexes(uint256 tokenId) private{
address owner = ownerOf(tokenId);
address currency = getUnderlyingAsset(tokenId);
_underlyingProtectionTokensMapping[tokenId] = 0;
_protectionCurrencyMapping[owner][currency].remove(tokenId);
}
/**
* @notice Returns C-OP total value
* @param tokenId ID of MProtection
*/
function getUnderlyingProtectionTotalValue(uint256 tokenId) public view returns(uint256){
address underlyingAsset = getUnderlyingAsset(tokenId);
uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset);
return div_(
mul_(
getUnderlyingStrikePrice(tokenId),
getUnderlyingAmount(tokenId)
),
assetDecimalsMantissa
);
}
/**
* @notice Returns C-OP locked value
* @param tokenId ID of MProtection
*/
function getUnderlyingProtectionLockedValue(uint256 tokenId) public view returns(uint256){
return _underlyingProtectionLockedValue[tokenId];
}
/**
* @notice get the amount of underlying asset that is locked
* @param tokenId CProtection tokenId
* @return amount locked
*/
function getUnderlyingProtectionLockedAmount(uint256 tokenId) public view returns(uint256){
address underlyingAsset = getUnderlyingAsset(tokenId);
uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset);
// calculates total protection value
uint256 protectionValue = div_(
mul_(
getUnderlyingAmount(tokenId),
getUnderlyingStrikePrice(tokenId)
),
assetDecimalsMantissa
);
// return value is lockedValue / totalValue * amount
return div_(
mul_(
getUnderlyingAmount(tokenId),
div_(
mul_(
_underlyingProtectionLockedValue[tokenId],
1e18
),
protectionValue
)
),
1e18
);
}
/**
* @notice Locks the given protection value as collateral optimization
* @param tokenId The MProtection token id
* @param value The value in stablecoin of protection to be locked as collateral optimization. 0 = max available optimization
* @return locked protection value
* TODO: convert semantic errors to standarized error codes
*/
function lockProtectionValue(uint256 tokenId, uint value) external returns(uint) {
//check if the protection belongs to the caller
require(isUserProtection(msg.sender, tokenId), "ERROR: CALLER IS NOT THE OWNER OF PROTECTION");
address currency = getUnderlyingAsset(tokenId);
Moartroller moartroller = Moartroller(_moartrollerAddress);
MToken mToken = moartroller.tokenAddressToMToken(currency);
require(moartroller.oracle().getUnderlyingPrice(mToken) <= getUnderlyingStrikePrice(tokenId), "ERROR: C-OP STRIKE PRICE IS LOWER THAN ASSET SPOT PRICE");
uint protectionTotalValue = getUnderlyingProtectionTotalValue(tokenId);
uint maxOptimizableValue = moartroller.getMaxOptimizableValue(mToken, ownerOf(tokenId));
// add protection locked value if any
uint protectionLockedValue = getUnderlyingProtectionLockedValue(tokenId);
if ( protectionLockedValue > 0) {
maxOptimizableValue = add_(maxOptimizableValue, protectionLockedValue);
}
uint valueToLock;
if (value != 0) {
// check if lock value is at most max optimizable value
require(value <= maxOptimizableValue, "ERROR: VALUE TO BE LOCKED EXCEEDS ALLOWED OPTIMIZATION VALUE");
// check if lock value is at most protection total value
require( value <= protectionTotalValue, "ERROR: VALUE TO BE LOCKED EXCEEDS PROTECTION TOTAL VALUE");
valueToLock = value;
} else {
// if we want to lock maximum protection value let's lock the value that is at most max optimizable value
if (protectionTotalValue > maxOptimizableValue) {
valueToLock = maxOptimizableValue;
} else {
valueToLock = protectionTotalValue;
}
}
_underlyingProtectionLockedValue[tokenId] = valueToLock;
emit LockValue(tokenId, getUnderlyingProtectionTokenId(tokenId), valueToLock);
return valueToLock;
}
function _setCopMapping(address newMapping) public onlyOwner {
_copMappingAddress = newMapping;
}
function _setMoartroller(address newMoartroller) public onlyOwner {
_moartrollerAddress = newMoartroller;
}
function _setMaturityWindow(uint256 maturityWindow) public onlyOwner {
emit MaturityWindowUpdated(maturityWindow);
_maturityWindow = maturityWindow;
}
// MAPPINGS
function getProtectionData(uint256 tokenId) public view returns (address, uint256, uint256, uint256, uint, uint){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getProtectionData(underlyingTokenId);
}
function getUnderlyingAsset(uint256 tokenId) public view returns (address){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingAsset(underlyingTokenId);
}
function getUnderlyingAmount(uint256 tokenId) public view returns (uint256){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingAmount(underlyingTokenId);
}
function getUnderlyingStrikePrice(uint256 tokenId) public view returns (uint){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingStrikePrice(underlyingTokenId);
}
function getUnderlyingDeadline(uint256 tokenId) public view returns (uint){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingDeadline(underlyingTokenId);
}
function getContractVersion() external override pure returns(string memory){
return "V1";
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "../MToken.sol";
interface PriceOracle {
/**
* @notice Get the underlying price of a mToken asset
* @param mToken The mToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(MToken mToken) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "./CarefulMath.sol";
import "./ExponentialNoError.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @dev Legacy contract for compatibility reasons with existing contracts that still use MathError
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath, ExponentialNoError {
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return balance The balance
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return success Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return success Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return success Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return remaining The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Moartroller.sol";
import "./AbstractInterestRateModel.sol";
abstract contract MTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @dev EIP-20 token name for this token
*/
string public name;
/**
* @dev EIP-20 token symbol for this token
*/
string public symbol;
/**
* @dev EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Underlying asset for this MToken
*/
address public underlying;
/**
* @dev Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal borrowRateMaxMantissa;
/**
* @dev Maximum fraction of interest that can be set aside for reserves
*/
uint internal reserveFactorMaxMantissa;
/**
* @dev Administrator for this contract
*/
address payable public admin;
/**
* @dev Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @dev Contract which oversees inter-mToken operations
*/
Moartroller public moartroller;
/**
* @dev Model which tells what the current interest rate should be
*/
AbstractInterestRateModel public interestRateModel;
/**
* @dev Initial exchange rate used when minting the first MTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @dev Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @dev Fraction of reserves currently set aside for other usage
*/
uint public reserveSplitFactorMantissa;
/**
* @dev Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @dev Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @dev Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @dev Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @dev Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @dev The Maximum Protection Moarosition (MPC) factor for collateral optimisation, default: 50% = 5000
*/
uint public maxProtectionComposition;
/**
* @dev The Maximum Protection Moarosition (MPC) mantissa, default: 1e5
*/
uint public maxProtectionCompositionMantissa;
/**
* @dev Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @dev Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
struct ProtectionUsage {
uint256 protectionValueUsed;
}
/**
* @dev Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
mapping (uint256 => ProtectionUsage) protectionsUsed;
}
struct AccrueInterestTempStorage{
uint interestAccumulated;
uint reservesAdded;
uint splitedReserves_1;
uint splitedReserves_2;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
}
/**
* @dev Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) public accountBorrows;
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./EIP20Interface.sol";
interface MTokenInterface {
/*** User contract ***/
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(address src, address dst, uint256 amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function getCash() external view returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
function getUnderlying() external view returns(address);
function sweepToken(EIP20Interface token) external;
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
interface MProxyInterface {
function proxyClaimReward(address asset, address recipient, uint amount) external;
function proxySplitReserves(address asset, uint amount) external;
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Interfaces/InterestRateModelInterface.sol";
abstract contract AbstractInterestRateModel is InterestRateModelInterface {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/**
* @title Careful Math
* @author MOAR
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "../MToken.sol";
import "../Utils/ExponentialNoError.sol";
interface MoartrollerInterface {
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `mTokenBalance` is the number of mTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint mTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
ExponentialNoError.Exp collateralFactor;
ExponentialNoError.Exp exchangeRate;
ExponentialNoError.Exp oraclePrice;
ExponentialNoError.Exp tokensToDenom;
}
/*** Assets You Are In ***/
function enterMarkets(address[] calldata mTokens) external returns (uint[] memory);
function exitMarket(address mToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address mToken, address minter, uint mintAmount) external returns (uint);
function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address mToken, address borrower, uint borrowAmount) external returns (uint);
function repayBorrowAllowed(
address mToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowAllowed(
address mTokenBorrowed,
address mTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function seizeAllowed(
address mTokenCollateral,
address mTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function transferAllowed(address mToken, address src, address dst, uint transferTokens) external returns (uint);
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeUserTokens(
address mTokenBorrowed,
address mTokenCollateral,
uint repayAmount,
address account) external view returns (uint, uint);
function getUserLockedAmount(MToken asset, address account) external view returns(uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
interface Versionable {
function getContractVersion() external pure returns (string memory);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./MToken.sol";
import "./Interfaces/PriceOracle.sol";
import "./Interfaces/LiquidityMathModelInterface.sol";
import "./Interfaces/LiquidationModelInterface.sol";
import "./MProtection.sol";
abstract contract UnitrollerAdminStorage {
/**
* @dev Administrator for this contract
*/
address public admin;
/**
* @dev Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @dev Active brains of Unitroller
*/
address public moartrollerImplementation;
/**
* @dev Pending brains of Unitroller
*/
address public pendingMoartrollerImplementation;
}
contract MoartrollerV1Storage is UnitrollerAdminStorage {
/**
* @dev Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @dev Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/**
* @dev Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @dev Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @dev Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => MToken[]) public accountAssets;
}
contract MoartrollerV2Storage is MoartrollerV1Storage {
struct Market {
// Whether or not this market is listed
bool isListed;
// Multiplier representing the most one can borrow against their collateral in this market.
// For instance, 0.9 to allow borrowing 90% of collateral value.
// Must be between 0 and 1, and stored as a mantissa.
uint collateralFactorMantissa;
// Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
// Whether or not this market receives MOAR
bool isMoared;
}
/**
* @dev Official mapping of mTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @dev The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
}
contract MoartrollerV3Storage is MoartrollerV2Storage {
struct MoarMarketState {
// The market's last updated moarBorrowIndex or moarSupplyIndex
uint224 index;
// The block number the index was last updated at
uint32 block;
}
/// @dev A list of all markets
MToken[] public allMarkets;
/// @dev The rate at which the flywheel distributes MOAR, per block
uint public moarRate;
/// @dev The portion of moarRate that each market currently receives
mapping(address => uint) public moarSpeeds;
/// @dev The MOAR market supply state for each market
mapping(address => MoarMarketState) public moarSupplyState;
/// @dev The MOAR market borrow state for each market
mapping(address => MoarMarketState) public moarBorrowState;
/// @dev The MOAR borrow index for each market for each supplier as of the last time they accrued MOAR
mapping(address => mapping(address => uint)) public moarSupplierIndex;
/// @dev The MOAR borrow index for each market for each borrower as of the last time they accrued MOAR
mapping(address => mapping(address => uint)) public moarBorrowerIndex;
/// @dev The MOAR accrued but not yet transferred to each user
mapping(address => uint) public moarAccrued;
}
contract MoartrollerV4Storage is MoartrollerV3Storage {
// @dev The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.
address public borrowCapGuardian;
// @dev Borrow caps enforced by borrowAllowed for each mToken address. Defaults to zero which corresponds to unlimited borrowing.
mapping(address => uint) public borrowCaps;
}
contract MoartrollerV5Storage is MoartrollerV4Storage {
/// @dev The portion of MOAR that each contributor receives per block
mapping(address => uint) public moarContributorSpeeds;
/// @dev Last block at which a contributor's MOAR rewards have been allocated
mapping(address => uint) public lastContributorBlock;
}
contract MoartrollerV6Storage is MoartrollerV5Storage {
/**
* @dev Moar token address
*/
address public moarToken;
/**
* @dev MProxy address
*/
address public mProxy;
/**
* @dev CProtection contract which can be used for collateral optimisation
*/
MProtection public cprotection;
/**
* @dev Mapping for basic token address to mToken
*/
mapping(address => MToken) public tokenAddressToMToken;
/**
* @dev Math model for liquidity calculation
*/
LiquidityMathModelInterface public liquidityMathModel;
/**
* @dev Liquidation model for liquidation related functions
*/
LiquidationModelInterface public liquidationModel;
/**
* @dev List of addresses with privileged access
*/
mapping(address => uint) public privilegedAddresses;
/**
* @dev Determines if reward claim feature is enabled
*/
bool public rewardClaimEnabled;
}
// Copyright (c) 2020 The UNION Protocol Foundation
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// import "hardhat/console.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
/**
* @title UNION Protocol Governance Token
* @dev Implementation of the basic standard token.
*/
contract UnionGovernanceToken is AccessControl, IERC20 {
using Address for address;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
/**
* @notice Struct for marking number of votes from a given block
* @member from
* @member votes
*/
struct VotingCheckpoint {
uint256 from;
uint256 votes;
}
/**
* @notice Struct for locked tokens
* @member amount
* @member releaseTime
* @member votable
*/
struct LockedTokens{
uint amount;
uint releaseTime;
bool votable;
}
/**
* @notice Struct for EIP712 Domain
* @member name
* @member version
* @member chainId
* @member verifyingContract
* @member salt
*/
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
bytes32 salt;
}
/**
* @notice Struct for EIP712 VotingDelegate call
* @member owner
* @member delegate
* @member nonce
* @member expirationTime
*/
struct VotingDelegate {
address owner;
address delegate;
uint256 nonce;
uint256 expirationTime;
}
/**
* @notice Struct for EIP712 Permit call
* @member owner
* @member spender
* @member value
* @member nonce
* @member deadline
*/
struct Permit {
address owner;
address spender;
uint256 value;
uint256 nonce;
uint256 deadline;
}
/**
* @notice Vote Delegation Events
*/
event VotingDelegateChanged(address indexed _owner, address indexed _fromDelegate, address indexed _toDelegate);
event VotingDelegateRemoved(address indexed _owner);
/**
* @notice Vote Balance Events
* Emmitted when a delegate account's vote balance changes at the time of a written checkpoint
*/
event VoteBalanceChanged(address indexed _account, uint256 _oldBalance, uint256 _newBalance);
/**
* @notice Transfer/Allocator Events
*/
event TransferStatusChanged(bool _newTransferStatus);
/**
* @notice Reversion Events
*/
event ReversionStatusChanged(bool _newReversionSetting);
/**
* @notice EIP-20 Approval event
*/
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
* @notice EIP-20 Transfer event
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Burn(address indexed _from, uint256 _value);
event AddressPermitted(address indexed _account);
event AddressRestricted(address indexed _account);
/**
* @dev AccessControl recognized roles
*/
bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN");
bytes32 public constant ROLE_ALLOCATE = keccak256("ROLE_ALLOCATE");
bytes32 public constant ROLE_GOVERN = keccak256("ROLE_GOVERN");
bytes32 public constant ROLE_MINT = keccak256("ROLE_MINT");
bytes32 public constant ROLE_LOCK = keccak256("ROLE_LOCK");
bytes32 public constant ROLE_TRUSTED = keccak256("ROLE_TRUSTED");
bytes32 public constant ROLE_TEST = keccak256("ROLE_TEST");
bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"
);
bytes32 public constant DELEGATE_TYPEHASH = keccak256(
"DelegateVote(address owner,address delegate,uint256 nonce,uint256 expirationTime)"
);
//keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
address private constant BURN_ADDRESS = address(0);
address public UPGT_CONTRACT_ADDRESS;
/**
* @dev hashes to support EIP-712 signing and validating, EIP712DOMAIN_SEPARATOR is set at time of contract instantiation and token minting.
*/
bytes32 public immutable EIP712DOMAIN_SEPARATOR;
/**
* @dev EIP-20 token name
*/
string public name = "UNION Protocol Governance Token";
/**
* @dev EIP-20 token symbol
*/
string public symbol = "UNN";
/**
* @dev EIP-20 token decimals
*/
uint8 public decimals = 18;
/**
* @dev Contract version
*/
string public constant version = '0.0.1';
/**
* @dev Initial amount of tokens
*/
uint256 private uint256_initialSupply = 100000000000 * 10**18;
/**
* @dev Total amount of tokens
*/
uint256 private uint256_totalSupply;
/**
* @dev Chain id
*/
uint256 private uint256_chain_id;
/**
* @dev general transfer restricted as function of public sale not complete
*/
bool private b_canTransfer = false;
/**
* @dev private variable that determines if failed EIP-20 functions revert() or return false. Reversion short-circuits the return from these functions.
*/
bool private b_revert = false; //false allows false return values
/**
* @dev Locked destinations list
*/
mapping(address => bool) private m_lockedDestinations;
/**
* @dev EIP-20 allowance and balance maps
*/
mapping(address => mapping(address => uint256)) private m_allowances;
mapping(address => uint256) private m_balances;
mapping(address => LockedTokens[]) private m_lockedBalances;
/**
* @dev nonces used by accounts to this contract for signing and validating signatures under EIP-712
*/
mapping(address => uint256) private m_nonces;
/**
* @dev delegated account may for off-line vote delegation
*/
mapping(address => address) private m_delegatedAccounts;
/**
* @dev delegated account inverse map is needed to live calculate voting power
*/
mapping(address => EnumerableSet.AddressSet) private m_delegatedAccountsInverseMap;
/**
* @dev indexed mapping of vote checkpoints for each account
*/
mapping(address => mapping(uint256 => VotingCheckpoint)) private m_votingCheckpoints;
/**
* @dev mapping of account addrresses to voting checkpoints
*/
mapping(address => uint256) private m_accountVotingCheckpoints;
/**
* @dev Contructor for the token
* @param _owner address of token contract owner
* @param _initialSupply of tokens generated by this contract
* Sets Transfer the total suppply to the owner.
* Sets default admin role to the owner.
* Sets ROLE_ALLOCATE to the owner.
* Sets ROLE_GOVERN to the owner.
* Sets ROLE_MINT to the owner.
* Sets EIP 712 Domain Separator.
*/
constructor(address _owner, uint256 _initialSupply) public {
//set internal contract references
UPGT_CONTRACT_ADDRESS = address(this);
//setup roles using AccessControl
_setupRole(DEFAULT_ADMIN_ROLE, _owner);
_setupRole(ROLE_ADMIN, _owner);
_setupRole(ROLE_ADMIN, _msgSender());
_setupRole(ROLE_ALLOCATE, _owner);
_setupRole(ROLE_ALLOCATE, _msgSender());
_setupRole(ROLE_TRUSTED, _owner);
_setupRole(ROLE_TRUSTED, _msgSender());
_setupRole(ROLE_GOVERN, _owner);
_setupRole(ROLE_MINT, _owner);
_setupRole(ROLE_LOCK, _owner);
_setupRole(ROLE_TEST, _owner);
m_balances[_owner] = _initialSupply;
uint256_totalSupply = _initialSupply;
b_canTransfer = false;
uint256_chain_id = _getChainId();
EIP712DOMAIN_SEPARATOR = _hash(EIP712Domain({
name : name,
version : version,
chainId : uint256_chain_id,
verifyingContract : address(this),
salt : keccak256(abi.encodePacked(name))
}
));
emit Transfer(BURN_ADDRESS, _owner, uint256_totalSupply);
}
/**
* @dev Sets transfer status to lock token transfer
* @param _canTransfer value can be true or false.
* disables transfer when set to false and enables transfer when true
* Only a member of ADMIN role can call to change transfer status
*/
function setCanTransfer(bool _canTransfer) public {
if(hasRole(ROLE_ADMIN, _msgSender())){
b_canTransfer = _canTransfer;
emit TransferStatusChanged(_canTransfer);
}
}
/**
* @dev Gets status of token transfer lock
* @return true or false status of whether the token can be transfered
*/
function getCanTransfer() public view returns (bool) {
return b_canTransfer;
}
/**
* @dev Sets transfer reversion status to either return false or throw on error
* @param _reversion value can be true or false.
* disables return of false values for transfer failures when set to false and enables transfer-related exceptions when true
* Only a member of ADMIN role can call to change transfer reversion status
*/
function setReversion(bool _reversion) public {
if(hasRole(ROLE_ADMIN, _msgSender()) ||
hasRole(ROLE_TEST, _msgSender())
) {
b_revert = _reversion;
emit ReversionStatusChanged(_reversion);
}
}
/**
* @dev Gets status of token transfer reversion
* @return true or false status of whether the token transfer failures return false or are reverted
*/
function getReversion() public view returns (bool) {
return b_revert;
}
/**
* @dev retrieve current chain id
* @return chain id
*/
function getChainId() public pure returns (uint256) {
return _getChainId();
}
/**
* @dev Retrieve current chain id
* @return chain id
*/
function _getChainId() internal pure returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* @dev Retrieve total supply of tokens
* @return uint256 total supply of tokens
*/
function totalSupply() public view override returns (uint256) {
return uint256_totalSupply;
}
/**
* Balance related functions
*/
/**
* @dev Retrieve balance of a specified account
* @param _account address of account holding balance
* @return uint256 balance of the specified account address
*/
function balanceOf(address _account) public view override returns (uint256) {
return m_balances[_account].add(_calculateReleasedBalance(_account));
}
/**
* @dev Retrieve locked balance of a specified account
* @param _account address of account holding locked balance
* @return uint256 locked balance of the specified account address
*/
function lockedBalanceOf(address _account) public view returns (uint256) {
return _calculateLockedBalance(_account);
}
/**
* @dev Retrieve lenght of locked balance array for specific address
* @param _account address of account holding locked balance
* @return uint256 locked balance array lenght
*/
function getLockedTokensListSize(address _account) public view returns (uint256){
require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions");
return m_lockedBalances[_account].length;
}
/**
* @dev Retrieve locked tokens struct from locked balance array for specific address
* @param _account address of account holding locked tokens
* @param _index index in array with locked tokens position
* @return amount of locked tokens
* @return releaseTime descibes time when tokens will be unlocked
* @return votable flag is describing votability of tokens
*/
function getLockedTokens(address _account, uint256 _index) public view returns (uint256 amount, uint256 releaseTime, bool votable){
require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions");
require(_index < m_lockedBalances[_account].length, "UPGT_ERROR: LockedTokens position doesn't exist on given index");
LockedTokens storage lockedTokens = m_lockedBalances[_account][_index];
return (lockedTokens.amount, lockedTokens.releaseTime, lockedTokens.votable);
}
/**
* @dev Calculates locked balance of a specified account
* @param _account address of account holding locked balance
* @return uint256 locked balance of the specified account address
*/
function _calculateLockedBalance(address _account) private view returns (uint256) {
uint256 lockedBalance = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].releaseTime > block.timestamp){
lockedBalance = lockedBalance.add(m_lockedBalances[_account][i].amount);
}
}
return lockedBalance;
}
/**
* @dev Calculates released balance of a specified account
* @param _account address of account holding released balance
* @return uint256 released balance of the specified account address
*/
function _calculateReleasedBalance(address _account) private view returns (uint256) {
uint256 releasedBalance = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){
releasedBalance = releasedBalance.add(m_lockedBalances[_account][i].amount);
}
}
return releasedBalance;
}
/**
* @dev Calculates locked votable balance of a specified account
* @param _account address of account holding locked votable balance
* @return uint256 locked votable balance of the specified account address
*/
function _calculateLockedVotableBalance(address _account) private view returns (uint256) {
uint256 lockedVotableBalance = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].votable == true){
lockedVotableBalance = lockedVotableBalance.add(m_lockedBalances[_account][i].amount);
}
}
return lockedVotableBalance;
}
/**
* @dev Moves released balance to normal balance for a specified account
* @param _account address of account holding released balance
*/
function _moveReleasedBalance(address _account) internal virtual{
uint256 releasedToMove = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){
releasedToMove = releasedToMove.add(m_lockedBalances[_account][i].amount);
m_lockedBalances[_account][i] = m_lockedBalances[_account][m_lockedBalances[_account].length - 1];
m_lockedBalances[_account].pop();
}
}
m_balances[_account] = m_balances[_account].add(releasedToMove);
}
/**
* Allowance related functinons
*/
/**
* @dev Retrieve the spending allowance for a token holder by a specified account
* @param _owner Token account holder
* @param _spender Account given allowance
* @return uint256 allowance value
*/
function allowance(address _owner, address _spender) public override virtual view returns (uint256) {
return m_allowances[_owner][_spender];
}
/**
* @dev Message sender approval to spend for a specified amount
* @param _spender address of party approved to spend
* @param _value amount of the approval
* @return boolean success status
* public wrapper for _approve, _owner is msg.sender
*/
function approve(address _spender, uint256 _value) public override returns (bool) {
bool success = _approveUNN(_msgSender(), _spender, _value);
if(!success && b_revert){
revert("UPGT_ERROR: APPROVE ERROR");
}
return success;
}
/**
* @dev Token owner approval of amount for specified spender
* @param _owner address of party that owns the tokens being granted approval for spending
* @param _spender address of party that is granted approval for spending
* @param _value amount approved for spending
* @return boolean approval status
* if _spender allownace for a given _owner is greater than 0,
* increaseAllowance/decreaseAllowance should be used to prevent a race condition whereby the spender is able to spend the total value of both the old and new allowance. _spender cannot be burn or this governance token contract address. Addresses github.com/ethereum/EIPs/issues738
*/
function _approveUNN(address _owner, address _spender, uint256 _value) internal returns (bool) {
bool retval = false;
if(_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
(m_allowances[_owner][_spender] == 0 || _value == 0)
){
m_allowances[_owner][_spender] = _value;
emit Approval(_owner, _spender, _value);
retval = true;
}
return retval;
}
/**
* @dev Increase spender allowance by specified incremental value
* @param _spender address of party that is granted approval for spending
* @param _addedValue specified incremental increase
* @return boolean increaseAllowance status
* public wrapper for _increaseAllowance, _owner restricted to msg.sender
*/
function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) {
bool success = _increaseAllowanceUNN(_msgSender(), _spender, _addedValue);
if(!success && b_revert){
revert("UPGT_ERROR: INCREASE ALLOWANCE ERROR");
}
return success;
}
/**
* @dev Allow owner to increase spender allowance by specified incremental value
* @param _owner address of the token owner
* @param _spender address of the token spender
* @param _addedValue specified incremental increase
* @return boolean return value status
* increase the number of tokens that an _owner provides as allowance to a _spender-- does not requrire the number of tokens allowed to be set first to 0. _spender cannot be either burn or this goverance token contract address.
*/
function _increaseAllowanceUNN(address _owner, address _spender, uint256 _addedValue) internal returns (bool) {
bool retval = false;
if(_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
_addedValue > 0
){
m_allowances[_owner][_spender] = m_allowances[_owner][_spender].add(_addedValue);
retval = true;
emit Approval(_owner, _spender, m_allowances[_owner][_spender]);
}
return retval;
}
/**
* @dev Decrease spender allowance by specified incremental value
* @param _spender address of party that is granted approval for spending
* @param _subtractedValue specified incremental decrease
* @return boolean success status
* public wrapper for _decreaseAllowance, _owner restricted to msg.sender
*/
//public wrapper for _decreaseAllowance, _owner restricted to msg.sender
function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) {
bool success = _decreaseAllowanceUNN(_msgSender(), _spender, _subtractedValue);
if(!success && b_revert){
revert("UPGT_ERROR: DECREASE ALLOWANCE ERROR");
}
return success;
}
/**
* @dev Allow owner to decrease spender allowance by specified incremental value
* @param _owner address of the token owner
* @param _spender address of the token spender
* @param _subtractedValue specified incremental decrease
* @return boolean return value status
* decrease the number of tokens than an _owner provdes as allowance to a _spender. A _spender cannot have a negative allowance. Does not require existing allowance to be set first to 0. _spender cannot be burn or this governance token contract address.
*/
function _decreaseAllowanceUNN(address _owner, address _spender, uint256 _subtractedValue) internal returns (bool) {
bool retval = false;
if(_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
_subtractedValue > 0 &&
m_allowances[_owner][_spender] >= _subtractedValue
){
m_allowances[_owner][_spender] = m_allowances[_owner][_spender].sub(_subtractedValue);
retval = true;
emit Approval(_owner, _spender, m_allowances[_owner][_spender]);
}
return retval;
}
/**
* LockedDestination related functions
*/
/**
* @dev Adds address as a designated destination for tokens when locked for allocation only
* @param _address Address of approved desitnation for movement during lock
* @return success in setting address as eligible for transfer independent of token lock status
*/
function setAsEligibleLockedDestination(address _address) public returns (bool) {
bool retVal = false;
if(hasRole(ROLE_ADMIN, _msgSender())){
m_lockedDestinations[_address] = true;
retVal = true;
}
return retVal;
}
/**
* @dev removes desitnation as eligible for transfer
* @param _address address being removed
*/
function removeEligibleLockedDestination(address _address) public {
if(hasRole(ROLE_ADMIN, _msgSender())){
require(_address != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
delete(m_lockedDestinations[_address]);
}
}
/**
* @dev checks whether a destination is eligible as recipient of transfer independent of token lock status
* @param _address address being checked
* @return whether desitnation is locked
*/
function checkEligibleLockedDesination(address _address) public view returns (bool) {
return m_lockedDestinations[_address];
}
/**
* @dev Adds address as a designated allocator that can move tokens when they are locked
* @param _address Address receiving the role of ROLE_ALLOCATE
* @return success as true or false
*/
function setAsAllocator(address _address) public returns (bool) {
bool retVal = false;
if(hasRole(ROLE_ADMIN, _msgSender())){
grantRole(ROLE_ALLOCATE, _address);
retVal = true;
}
return retVal;
}
/**
* @dev Removes address as a designated allocator that can move tokens when they are locked
* @param _address Address being removed from the ROLE_ALLOCATE
* @return success as true or false
*/
function removeAsAllocator(address _address) public returns (bool) {
bool retVal = false;
if(hasRole(ROLE_ADMIN, _msgSender())){
if(hasRole(ROLE_ALLOCATE, _address)){
revokeRole(ROLE_ALLOCATE, _address);
retVal = true;
}
}
return retVal;
}
/**
* @dev Checks to see if an address has the role of being an allocator
* @param _address Address being checked for ROLE_ALLOCATE
* @return true or false whether the address has ROLE_ALLOCATE assigned
*/
function checkAsAllocator(address _address) public view returns (bool) {
return hasRole(ROLE_ALLOCATE, _address);
}
/**
* Transfer related functions
*/
/**
* @dev Public wrapper for transfer function to move tokens of specified value to a given address
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @return status of transfer success
*/
function transfer(address _to, uint256 _value) external override returns (bool) {
bool success = _transferUNN(_msgSender(), _to, _value);
if(!success && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER");
}
return success;
}
/**
* @dev Transfer token for a specified address, but cannot transfer tokens to either the burn or this governance contract address. Also moves voting delegates as required.
* @param _owner The address owner where transfer originates
* @param _to The address to transfer to
* @param _value The amount to be transferred
* @return status of transfer success
*/
function _transferUNN(address _owner, address _to, uint256 _value) internal returns (bool) {
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) {
if(
_to != BURN_ADDRESS &&
_to != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value >= 0)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_balances[_to] = m_balances[_to].add(_value);
retval = true;
//need to move voting delegates with transfer of tokens
retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value);
emit Transfer(_owner, _to, _value);
}
}
return retval;
}
/**
* @dev Public wrapper for transferAndLock function to move tokens of specified value to a given address and lock them for a period of time
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
* Requires ROLE_LOCK
*/
function transferAndLock(address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) {
bool retval = false;
if(hasRole(ROLE_LOCK, _msgSender())){
retval = _transferAndLock(msg.sender, _to, _value, _releaseTime, _votable);
}
if(!retval && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER AND LOCK");
}
return retval;
}
/**
* @dev Transfers tokens of specified value to a given address and lock them for a period of time
* @param _owner The address owner where transfer originates
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
*/
function _transferAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal virtual returns (bool){
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) {
if(
_to != BURN_ADDRESS &&
_to != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value >= 0)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable));
retval = true;
//need to move voting delegates with transfer of tokens
// retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value);
emit Transfer(_owner, _to, _value);
}
}
return retval;
}
/**
* @dev Public wrapper for transferFrom function
* @param _owner The address to transfer from
* @param _spender cannot be the burn address
* @param _value The amount to be transferred
* @return status of transferFrom success
* _spender cannot be either this goverance token contract or burn
*/
function transferFrom(address _owner, address _spender, uint256 _value) external override returns (bool) {
bool success = _transferFromUNN(_owner, _spender, _value);
if(!success && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER FROM");
}
return success;
}
/**
* @dev Transfer token for a specified address. _spender cannot be either this goverance token contract or burn
* @param _owner The address to transfer from
* @param _spender cannot be the burn address
* @param _value The amount to be transferred
* @return status of transferFrom success
* _spender cannot be either this goverance token contract or burn
*/
function _transferFromUNN(address _owner, address _spender, uint256 _value) internal returns (bool) {
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_spender)) {
if(
_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value > 0) &&
(m_allowances[_owner][_msgSender()] >= _value)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_balances[_spender] = m_balances[_spender].add(_value);
m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value);
retval = true;
//need to move delegates that exist for this owner in line with transfer
retval = retval && _moveVotingDelegates(_owner, _spender, _value);
emit Transfer(_owner, _spender, _value);
}
}
return retval;
}
/**
* @dev Public wrapper for transferFromAndLock function to move tokens of specified value from given address to another address and lock them for a period of time
* @param _owner The address owner where transfer originates
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
* Requires ROLE_LOCK
*/
function transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) {
bool retval = false;
if(hasRole(ROLE_LOCK, _msgSender())){
retval = _transferFromAndLock(_owner, _to, _value, _releaseTime, _votable);
}
if(!retval && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER FROM AND LOCK");
}
return retval;
}
/**
* @dev Transfers tokens of specified value from a given address to another address and lock them for a period of time
* @param _owner The address owner where transfer originates
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
*/
function _transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal returns (bool) {
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) {
if(
_to != BURN_ADDRESS &&
_to != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value > 0) &&
(m_allowances[_owner][_msgSender()] >= _value)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable));
m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value);
retval = true;
//need to move delegates that exist for this owner in line with transfer
// retval = retval && _moveVotingDelegates(_owner, _to, _value);
emit Transfer(_owner, _to, _value);
}
}
return retval;
}
/**
* @dev Public function to burn tokens
* @param _value number of tokens to be burned
* @return whether tokens were burned
* Only ROLE_MINTER may burn tokens
*/
function burn(uint256 _value) external returns (bool) {
bool success = _burn(_value);
if(!success && b_revert){
revert("UPGT_ERROR: FAILED TO BURN");
}
return success;
}
/**
* @dev Private function Burn tokens
* @param _value number of tokens to be burned
* @return bool whether the tokens were burned
* only a minter may burn tokens, meaning that tokens being burned must be previously send to a ROLE_MINTER wallet.
*/
function _burn(uint256 _value) internal returns (bool) {
bool retval = false;
if(hasRole(ROLE_MINT, _msgSender()) &&
(m_balances[_msgSender()] >= _value)
){
m_balances[_msgSender()] -= _value;
uint256_totalSupply = uint256_totalSupply.sub(_value);
retval = true;
emit Burn(_msgSender(), _value);
}
return retval;
}
/**
* Voting related functions
*/
/**
* @dev Public wrapper for _calculateVotingPower function which calulates voting power
* @dev voting power = balance + locked votable balance + delegations
* @return uint256 voting power
*/
function calculateVotingPower() public view returns (uint256) {
return _calculateVotingPower(_msgSender());
}
/**
* @dev Calulates voting power of specified address
* @param _account address of token holder
* @return uint256 voting power
*/
function _calculateVotingPower(address _account) private view returns (uint256) {
uint256 votingPower = m_balances[_account].add(_calculateLockedVotableBalance(_account));
for (uint i=0; i<m_delegatedAccountsInverseMap[_account].length(); i++) {
if(m_delegatedAccountsInverseMap[_account].at(i) != address(0)){
address delegatedAccount = m_delegatedAccountsInverseMap[_account].at(i);
votingPower = votingPower.add(m_balances[delegatedAccount]).add(_calculateLockedVotableBalance(delegatedAccount));
}
}
return votingPower;
}
/**
* @dev Moves a number of votes from a token holder to a designated representative
* @param _source address of token holder
* @param _destination address of voting delegate
* @param _amount of voting delegation transfered to designated representative
* @return bool whether move was successful
* Requires ROLE_TEST
*/
function moveVotingDelegates(
address _source,
address _destination,
uint256 _amount) public returns (bool) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _moveVotingDelegates(_source, _destination, _amount);
}
/**
* @dev Moves a number of votes from a token holder to a designated representative
* @param _source address of token holder
* @param _destination address of voting delegate
* @param _amount of voting delegation transfered to designated representative
* @return bool whether move was successful
*/
function _moveVotingDelegates(
address _source,
address _destination,
uint256 _amount
) internal returns (bool) {
if(_source != _destination && _amount > 0) {
if(_source != BURN_ADDRESS) {
uint256 sourceNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_source];
uint256 sourceNumberOfVotingCheckpointsOriginal = (sourceNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][sourceNumberOfVotingCheckpoints.sub(1)].votes : 0;
if(sourceNumberOfVotingCheckpointsOriginal >= _amount) {
uint256 sourceNumberOfVotingCheckpointsNew = sourceNumberOfVotingCheckpointsOriginal.sub(_amount);
_writeVotingCheckpoint(_source, sourceNumberOfVotingCheckpoints, sourceNumberOfVotingCheckpointsOriginal, sourceNumberOfVotingCheckpointsNew);
}
}
if(_destination != BURN_ADDRESS) {
uint256 destinationNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_destination];
uint256 destinationNumberOfVotingCheckpointsOriginal = (destinationNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][destinationNumberOfVotingCheckpoints.sub(1)].votes : 0;
uint256 destinationNumberOfVotingCheckpointsNew = destinationNumberOfVotingCheckpointsOriginal.add(_amount);
_writeVotingCheckpoint(_destination, destinationNumberOfVotingCheckpoints, destinationNumberOfVotingCheckpointsOriginal, destinationNumberOfVotingCheckpointsNew);
}
}
return true;
}
/**
* @dev Writes voting checkpoint for a given voting delegate
* @param _votingDelegate exercising votes
* @param _numberOfVotingCheckpoints number of voting checkpoints for current vote
* @param _oldVotes previous number of votes
* @param _newVotes new number of votes
* Public function for writing voting checkpoint
* Requires ROLE_TEST
*/
function writeVotingCheckpoint(
address _votingDelegate,
uint256 _numberOfVotingCheckpoints,
uint256 _oldVotes,
uint256 _newVotes) public {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
_writeVotingCheckpoint(_votingDelegate, _numberOfVotingCheckpoints, _oldVotes, _newVotes);
}
/**
* @dev Writes voting checkpoint for a given voting delegate
* @param _votingDelegate exercising votes
* @param _numberOfVotingCheckpoints number of voting checkpoints for current vote
* @param _oldVotes previous number of votes
* @param _newVotes new number of votes
* Private function for writing voting checkpoint
*/
function _writeVotingCheckpoint(
address _votingDelegate,
uint256 _numberOfVotingCheckpoints,
uint256 _oldVotes,
uint256 _newVotes) internal {
if(_numberOfVotingCheckpoints > 0 && m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints.sub(1)].from == block.number) {
m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints-1].votes = _newVotes;
}
else {
m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints] = VotingCheckpoint(block.number, _newVotes);
_numberOfVotingCheckpoints = _numberOfVotingCheckpoints.add(1);
}
emit VoteBalanceChanged(_votingDelegate, _oldVotes, _newVotes);
}
/**
* @dev Calculate account votes as of a specific block
* @param _account address whose votes are counted
* @param _blockNumber from which votes are being counted
* @return number of votes counted
*/
function getVoteCountAtBlock(
address _account,
uint256 _blockNumber) public view returns (uint256) {
uint256 voteCount = 0;
if(_blockNumber < block.number) {
if(m_accountVotingCheckpoints[_account] != 0) {
if(m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].from <= _blockNumber) {
voteCount = m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].votes;
}
else if(m_votingCheckpoints[_account][0].from > _blockNumber) {
voteCount = 0;
}
else {
uint256 lower = 0;
uint256 upper = m_accountVotingCheckpoints[_account].sub(1);
while(upper > lower) {
uint256 center = upper.sub((upper.sub(lower).div(2)));
VotingCheckpoint memory votingCheckpoint = m_votingCheckpoints[_account][center];
if(votingCheckpoint.from == _blockNumber) {
voteCount = votingCheckpoint.votes;
break;
}
else if(votingCheckpoint.from < _blockNumber) {
lower = center;
}
else {
upper = center.sub(1);
}
}
}
}
}
return voteCount;
}
/**
* @dev Vote Delegation Functions
* @param _to address where message sender is assigning votes
* @return success of message sender delegating vote
* delegate function does not allow assignment to burn
*/
function delegateVote(address _to) public returns (bool) {
return _delegateVote(_msgSender(), _to);
}
/**
* @dev Delegate votes from token holder to another address
* @param _from Token holder
* @param _toDelegate Address that will be delegated to for purpose of voting
* @return success as to whether delegation has been a success
*/
function _delegateVote(
address _from,
address _toDelegate) internal returns (bool) {
bool retval = false;
if(_toDelegate != BURN_ADDRESS) {
address currentDelegate = m_delegatedAccounts[_from];
uint256 fromAccountBalance = m_balances[_from].add(_calculateLockedVotableBalance(_from));
address oldToDelegate = m_delegatedAccounts[_from];
m_delegatedAccounts[_from] = _toDelegate;
m_delegatedAccountsInverseMap[oldToDelegate].remove(_from);
if(_from != _toDelegate){
m_delegatedAccountsInverseMap[_toDelegate].add(_from);
}
retval = true;
retval = retval && _moveVotingDelegates(currentDelegate, _toDelegate, fromAccountBalance);
if(retval) {
if(_from == _toDelegate){
emit VotingDelegateRemoved(_from);
}
else{
emit VotingDelegateChanged(_from, currentDelegate, _toDelegate);
}
}
}
return retval;
}
/**
* @dev Revert voting delegate control to owner account
* @param _account The account that has delegated its vote
* @return success of reverting delegation to owner
*/
function _revertVotingDelegationToOwner(address _account) internal returns (bool) {
return _delegateVote(_account, _account);
}
/**
* @dev Used by an message sending account to recall its voting delegates
* @return success of reverting delegation to owner
*/
function recallVotingDelegate() public returns (bool) {
return _revertVotingDelegationToOwner(_msgSender());
}
/**
* @dev Retrieve the voting delegate for a specified account
* @param _account The account that has delegated its vote
*/
function getVotingDelegate(address _account) public view returns (address) {
return m_delegatedAccounts[_account];
}
/**
* EIP-712 related functions
*/
/**
* @dev EIP-712 Ethereum Typed Structured Data Hashing and Signing for Allocation Permit
* @param _owner address of token owner
* @param _spender address of designated spender
* @param _value value permitted for spend
* @param _deadline expiration of signature
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
*/
function permit(
address _owner,
address _spender,
uint256 _value,
uint256 _deadline,
uint8 _ecv,
bytes32 _ecr,
bytes32 _ecs
) external returns (bool) {
require(block.timestamp <= _deadline, "UPGT_ERROR: wrong timestamp");
require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect");
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
EIP712DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, m_nonces[_owner]++, _deadline))
)
);
require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user");
require(_owner != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
return _approveUNN(_owner, _spender, _value);
}
/**
* @dev EIP-712 ETH Typed Structured Data Hashing and Signing for Delegate Vote
* @param _owner address of token owner
* @param _delegate address of voting delegate
* @param _expiretimestamp expiration of delegation signature
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
* @ @return bool true or false depedening on whether vote was successfully delegated
*/
function delegateVoteBySignature(
address _owner,
address _delegate,
uint256 _expiretimestamp,
uint8 _ecv,
bytes32 _ecr,
bytes32 _ecs
) external returns (bool) {
require(block.timestamp <= _expiretimestamp, "UPGT_ERROR: wrong timestamp");
require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect");
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
EIP712DOMAIN_SEPARATOR,
_hash(VotingDelegate(
{
owner : _owner,
delegate : _delegate,
nonce : m_nonces[_owner]++,
expirationTime : _expiretimestamp
})
)
)
);
require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user");
require(_owner!= BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
return _delegateVote(_owner, _delegate);
}
/**
* @dev Public hash EIP712Domain struct for EIP-712
* @param _eip712Domain EIP712Domain struct
* @return bytes32 hash of _eip712Domain
* Requires ROLE_TEST
*/
function hashEIP712Domain(EIP712Domain memory _eip712Domain) public view returns (bytes32) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _hash(_eip712Domain);
}
/**
* @dev Hash Delegate struct for EIP-712
* @param _delegate VotingDelegate struct
* @return bytes32 hash of _delegate
* Requires ROLE_TEST
*/
function hashDelegate(VotingDelegate memory _delegate) public view returns (bytes32) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _hash(_delegate);
}
/**
* @dev Public hash Permit struct for EIP-712
* @param _permit Permit struct
* @return bytes32 hash of _permit
* Requires ROLE_TEST
*/
function hashPermit(Permit memory _permit) public view returns (bytes32) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _hash(_permit);
}
/**
* @param _digest signed, hashed message
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
* @return address of the validated signer
* based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function
* Requires ROLE_TEST
*/
function recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) public view returns (address) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _recoverSigner(_digest, _ecv, _ecr, _ecs);
}
/**
* @dev Private hash EIP712Domain struct for EIP-712
* @param _eip712Domain EIP712Domain struct
* @return bytes32 hash of _eip712Domain
*/
function _hash(EIP712Domain memory _eip712Domain) internal pure returns (bytes32) {
return keccak256(
abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256(bytes(_eip712Domain.name)),
keccak256(bytes(_eip712Domain.version)),
_eip712Domain.chainId,
_eip712Domain.verifyingContract,
_eip712Domain.salt
)
);
}
/**
* @dev Private hash Delegate struct for EIP-712
* @param _delegate VotingDelegate struct
* @return bytes32 hash of _delegate
*/
function _hash(VotingDelegate memory _delegate) internal pure returns (bytes32) {
return keccak256(
abi.encode(
DELEGATE_TYPEHASH,
_delegate.owner,
_delegate.delegate,
_delegate.nonce,
_delegate.expirationTime
)
);
}
/**
* @dev Private hash Permit struct for EIP-712
* @param _permit Permit struct
* @return bytes32 hash of _permit
*/
function _hash(Permit memory _permit) internal pure returns (bytes32) {
return keccak256(abi.encode(
PERMIT_TYPEHASH,
_permit.owner,
_permit.spender,
_permit.value,
_permit.nonce,
_permit.deadline
));
}
/**
* @dev Recover signer information from provided digest
* @param _digest signed, hashed message
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
* @return address of the validated signer
* based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function
*/
function _recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) 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.
if(uint256(_ecs) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if(_ecv != 27 && _ecv != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(_digest, _ecv, _ecr, _ecs);
require(signer != BURN_ADDRESS, "ECDSA: invalid signature");
return signer;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../Interfaces/EIP20Interface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title SafeEIP20
* @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.
* This is a forked version of Openzeppelin's SafeERC20 contract but supporting
* EIP20Interface instead of Openzeppelin's IERC20
* 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 SafeEIP20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(EIP20Interface token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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 experimental ABIEncoderV2;
import "./PriceOracle.sol";
import "./MoartrollerInterface.sol";
pragma solidity ^0.6.12;
interface LiquidationModelInterface {
function liquidateCalculateSeizeUserTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint);
function liquidateCalculateSeizeTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint);
struct LiquidateCalculateSeizeUserTokensArgumentsSet {
PriceOracle oracle;
MoartrollerInterface moartroller;
address mTokenBorrowed;
address mTokenCollateral;
uint actualRepayAmount;
address accountForLiquidation;
uint liquidationIncentiveMantissa;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
/**
* @title MOAR's InterestRateModel Interface
* @author MOAR
*/
interface InterestRateModelInterface {
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC721Upgradeable.sol";
import "./IERC721MetadataUpgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "../../introspection/ERC165Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/EnumerableSetUpgradeable.sol";
import "../../utils/EnumerableMapUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap;
using StringsUpgradeable for uint256;
// 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;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSetUpgradeable.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMapUpgradeable.UintToAddressMap private _tokenOwners;
// 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;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @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 _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @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 _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721Upgradeable.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @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 = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721Upgradeable.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `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);
_holderTokens[to].add(tokenId);
_tokenOwners.set(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 = ERC721Upgradeable.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(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(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @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()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721ReceiverUpgradeable(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @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 { }
uint256[41] private __gap;
}
// 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: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// 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(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// 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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
interface CopMappingInterface {
function getTokenAddress() external view returns (address);
function getProtectionData(uint256 underlyingTokenId) external view returns (address, uint256, uint256, uint256, uint, uint);
function getUnderlyingAsset(uint256 underlyingTokenId) external view returns (address);
function getUnderlyingAmount(uint256 underlyingTokenId) external view returns (uint256);
function getUnderlyingStrikePrice(uint256 underlyingTokenId) external view returns (uint);
function getUnderlyingDeadline(uint256 underlyingTokenId) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/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.
*/
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;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165Upgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
uint256[49] private __gap;
}
// 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 SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// 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(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// 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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMapUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry 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.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
/**
* @dev Converts a `uint256` to its ASCII `string` 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);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// 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 IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
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/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.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, 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 {
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 `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());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
// 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.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: BSD-3-Clause
pragma solidity ^0.6.12;
import "./MToken.sol";
import "./Interfaces/MErc20Interface.sol";
import "./Moartroller.sol";
import "./AbstractInterestRateModel.sol";
import "./Interfaces/EIP20Interface.sol";
import "./Utils/SafeEIP20.sol";
/**
* @title MOAR's MErc20 Contract
* @notice MTokens which wrap an EIP-20 underlying
*/
contract MErc20 is MToken, MErc20Interface {
using SafeEIP20 for EIP20Interface;
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param moartroller_ The address of the Moartroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function init(address underlying_,
Moartroller moartroller_,
AbstractInterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// MToken initialize does the bulk of the work
super.init(moartroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives mTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external override returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
/**
* @notice Sender redeems mTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of mTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external override returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems mTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external override returns (uint) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external override returns (uint) {
return borrowInternal(borrowAmount);
}
function borrowFor(address payable borrower, uint borrowAmount) external override returns (uint) {
return borrowForInternal(borrower, borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external override returns (uint) {
(uint err,) = repayBorrowInternal(repayAmount);
return err;
}
/**
* @notice Sender repays a borrow belonging to borrower.
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external override returns (uint) {
(uint err,) = repayBorrowBehalfInternal(borrower, repayAmount);
return err;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this mToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param mTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, MToken mTokenCollateral) external override returns (uint) {
(uint err,) = liquidateBorrowInternal(borrower, repayAmount, mTokenCollateral);
return err;
}
/**
* @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock)
* @param token The address of the ERC-20 token to sweep
*/
function sweepToken(EIP20Interface token) override external {
require(address(token) != underlying, "MErc20::sweepToken: can not sweep underlying token");
uint256 balance = token.balanceOf(address(this));
token.safeTransfer(admin, balance);
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external override returns (uint) {
return _addReservesInternal(addAmount);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal override view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*`
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal override returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
uint balanceBefore = token.balanceOf(address(this));
token.safeTransferFrom(from, address(this), amount);
// Calculate the amount that was *actually* transferred
uint balanceAfter = token.balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal override {
EIP20Interface token = EIP20Interface(underlying);
token.safeTransfer(to, amount);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "../MToken.sol";
interface MErc20Interface {
/*** User contract ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function borrowFor(address payable borrower, uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, MToken mTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
| * @dev Delegate votes from token holder to another address @param _from Token holder @param _toDelegate Address that will be delegated to for purpose of voting @return success as to whether delegation has been a success/ | function _delegateVote(
address _from,
address _toDelegate) internal returns (bool) {
bool retval = false;
if(_toDelegate != BURN_ADDRESS) {
address currentDelegate = m_delegatedAccounts[_from];
uint256 fromAccountBalance = m_balances[_from].add(_calculateLockedVotableBalance(_from));
address oldToDelegate = m_delegatedAccounts[_from];
m_delegatedAccounts[_from] = _toDelegate;
m_delegatedAccountsInverseMap[oldToDelegate].remove(_from);
if(_from != _toDelegate){
m_delegatedAccountsInverseMap[_toDelegate].add(_from);
}
retval = true;
retval = retval && _moveVotingDelegates(currentDelegate, _toDelegate, fromAccountBalance);
if(retval) {
if(_from == _toDelegate){
emit VotingDelegateRemoved(_from);
}
else{
emit VotingDelegateChanged(_from, currentDelegate, _toDelegate);
}
}
}
return retval;
}
| 11,818,600 | [
1,
9586,
19588,
628,
1147,
10438,
358,
4042,
1758,
225,
389,
2080,
3155,
10438,
225,
389,
869,
9586,
5267,
716,
903,
506,
30055,
358,
364,
13115,
434,
331,
17128,
327,
2216,
487,
358,
2856,
23595,
711,
2118,
279,
2216,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
225,
445,
389,
22216,
19338,
12,
203,
565,
1758,
389,
2080,
16,
7010,
565,
1758,
389,
869,
9586,
13,
2713,
1135,
261,
6430,
13,
288,
203,
565,
1426,
5221,
273,
629,
31,
203,
565,
309,
24899,
869,
9586,
480,
605,
8521,
67,
15140,
13,
288,
203,
1377,
1758,
783,
9586,
273,
312,
67,
3771,
1332,
690,
13971,
63,
67,
2080,
15533,
203,
1377,
2254,
5034,
628,
3032,
13937,
273,
312,
67,
70,
26488,
63,
67,
2080,
8009,
1289,
24899,
11162,
8966,
58,
352,
429,
13937,
24899,
2080,
10019,
203,
1377,
1758,
1592,
774,
9586,
273,
312,
67,
3771,
1332,
690,
13971,
63,
67,
2080,
15533,
203,
1377,
312,
67,
3771,
1332,
690,
13971,
63,
67,
2080,
65,
273,
389,
869,
9586,
31,
203,
203,
1377,
312,
67,
3771,
1332,
690,
13971,
16376,
863,
63,
1673,
774,
9586,
8009,
4479,
24899,
2080,
1769,
203,
1377,
309,
24899,
2080,
480,
389,
869,
9586,
15329,
203,
3639,
312,
67,
3771,
1332,
690,
13971,
16376,
863,
63,
67,
869,
9586,
8009,
1289,
24899,
2080,
1769,
203,
1377,
289,
203,
203,
1377,
5221,
273,
638,
31,
203,
1377,
5221,
273,
5221,
597,
389,
8501,
58,
17128,
15608,
815,
12,
2972,
9586,
16,
389,
869,
9586,
16,
628,
3032,
13937,
1769,
203,
1377,
309,
12,
18341,
13,
288,
203,
3639,
309,
24899,
2080,
422,
389,
869,
9586,
15329,
203,
1850,
3626,
776,
17128,
9586,
10026,
24899,
2080,
1769,
203,
3639,
289,
203,
3639,
469,
95,
203,
1850,
3626,
776,
17128,
9586,
5033,
24899,
2080,
16,
783,
9586,
16,
389,
869,
2
]
|
./full_match/42161/0xEB5C537eE9cc09e55556ea4FDee34D366405dE09/sources/contracts/core/vaults/ConcentratedLPVault.sol | ============================================================= Initialize ============================================================= | contract ConcentratedLPVault is TokenizedVault {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using SignedSafeMath for int256;
using FixedPointMathLib for uint256;
IDEXPool pool;
int24 private _initialTickLower;
int24 private _initialTickUpper;
constructor(address depostiableToken_, address dexPoolAddress_, int24 initialTickLower_, int24 initialTickUpper_)
TokenizedVault(depostiableToken_)
pragma solidity ^0.8.9;
{
pool = IDEXPool(dexPoolAddress_);
setInitialTicks(initialTickLower_, initialTickUpper_);
}
function setInitialTicks(int24 initialTickLower_, int24 initialTickUpper_) public onlyRole(DEFAULT_ADMIN_ROLE) {
_initialTickLower = initialTickLower_;
_initialTickUpper = initialTickUpper_;
}
function setDepositableToken(address _depositableToken)
external
virtual
override
onlyRole(DEFAULT_ADMIN_ROLE)
whenNoActiveDeposits
{
address[] memory tokens = pool.getTokens();
require(_depositableToken == tokens[0] || _depositableToken == tokens[1], "Only pair tokens");
depositableToken = IERC20(_depositableToken);
}
function totalValueLocked() public view override virtual returns (uint256[] memory amounts) {
amounts = new uint256[](2);
uint256 totalLiquidity = pool.getTotalLiquidity();
if (totalLiquidity == 0) return amounts;
amounts = pool.getTokenAmounts(false);
}
function convertToShares(uint256[] memory assets) public view override returns (uint256 shares) {
uint256 price = pool.getPrice();
uint256 contributionAmount0 = assets[0].add(FullMath.mulDiv(assets[1], FixedPoint96.Q96, price));
uint256 tvlAmount0 = assets[2].add(FullMath.mulDiv(assets[3], FixedPoint96.Q96, price));
(uint256 collectableFee0, uint256 collectableFee1) = pool.getFeesToCollect();
uint256 feesAmount0 = collectableFee0.add(FullMath.mulDiv(collectableFee1, FixedPoint96.Q96, price));
uint256 totalShares = totalSupply();
if (totalShares == 0) {
address[] memory tokens = pool.getTokens();
uint256 mutiplier = 10 ** _decimalDifferences(tokens[0], tokens[1]);
return contributionAmount0.mul(mutiplier);
}
shares = contributionAmount0.mulDivDown(totalShares, tvlAmount0 + feesAmount0);
}
function convertToShares(uint256[] memory assets) public view override returns (uint256 shares) {
uint256 price = pool.getPrice();
uint256 contributionAmount0 = assets[0].add(FullMath.mulDiv(assets[1], FixedPoint96.Q96, price));
uint256 tvlAmount0 = assets[2].add(FullMath.mulDiv(assets[3], FixedPoint96.Q96, price));
(uint256 collectableFee0, uint256 collectableFee1) = pool.getFeesToCollect();
uint256 feesAmount0 = collectableFee0.add(FullMath.mulDiv(collectableFee1, FixedPoint96.Q96, price));
uint256 totalShares = totalSupply();
if (totalShares == 0) {
address[] memory tokens = pool.getTokens();
uint256 mutiplier = 10 ** _decimalDifferences(tokens[0], tokens[1]);
return contributionAmount0.mul(mutiplier);
}
shares = contributionAmount0.mulDivDown(totalShares, tvlAmount0 + feesAmount0);
}
function _decimalDifferences(address token0, address token1) private view returns (uint8 diff) {
uint8 token0Decimal = ERC20(token0).decimals();
uint8 token1Decimal = ERC20(token1).decimals();
diff = token0Decimal > token1Decimal ? token0Decimal - token1Decimal : token1Decimal - token0Decimal;
}
function convertToAssets(uint256 shares) public view override returns (uint256[] memory assets) {
assets = new uint256[](3);
uint256 totalShares = totalSupply();
if (totalShares == 0) return assets;
uint256 proportionX96 = FullMath.mulDiv(shares, FixedPoint96.Q96, totalShares);
uint256 totalLiquidity = uint256(pool.getTotalLiquidity());
assets[0] = totalLiquidity.mulDivDown(proportionX96, FixedPoint96.Q96);
(uint256 collectableFee0, uint256 collectableFee1) = pool.getFeesToCollect();
assets[1] = collectableFee0.mulDivDown(proportionX96, FixedPoint96.Q96);
assets[2] = collectableFee1.mulDivDown(proportionX96, FixedPoint96.Q96);
}
function _processDepositAmount(uint256 depositAmount) internal override returns (uint256[] memory assets) {
address[] memory tokens = pool.getTokens();
address depositableTokenAddress = address(depositableToken);
(uint256 amount0Desired, uint256 amount1Desired) = tokens[0] == depositableTokenAddress ? _divideToken0(depositAmount) : _divideToken1(depositAmount);
TransferHelper.safeApprove(address(tokens[0]), address(pool), amount0Desired);
TransferHelper.safeApprove(address(tokens[1]), address(pool), amount1Desired);
assets = new uint256[](4);
uint256[] memory tvl = totalValueLocked();
assets[2] = tvl[0];
assets[3] = tvl[1];
if (pool.getTokenId() == 0) {
(, , assets[0], assets[1]) = pool.mintNewPosition(amount0Desired, amount1Desired, _initialTickLower, _initialTickUpper, msg.sender);
}
else {
(, assets[0], assets[1]) = pool.increaseLiquidity(amount0Desired, amount1Desired, msg.sender);
}
}
function _processDepositAmount(uint256 depositAmount) internal override returns (uint256[] memory assets) {
address[] memory tokens = pool.getTokens();
address depositableTokenAddress = address(depositableToken);
(uint256 amount0Desired, uint256 amount1Desired) = tokens[0] == depositableTokenAddress ? _divideToken0(depositAmount) : _divideToken1(depositAmount);
TransferHelper.safeApprove(address(tokens[0]), address(pool), amount0Desired);
TransferHelper.safeApprove(address(tokens[1]), address(pool), amount1Desired);
assets = new uint256[](4);
uint256[] memory tvl = totalValueLocked();
assets[2] = tvl[0];
assets[3] = tvl[1];
if (pool.getTokenId() == 0) {
(, , assets[0], assets[1]) = pool.mintNewPosition(amount0Desired, amount1Desired, _initialTickLower, _initialTickUpper, msg.sender);
}
else {
(, assets[0], assets[1]) = pool.increaseLiquidity(amount0Desired, amount1Desired, msg.sender);
}
}
function _processDepositAmount(uint256 depositAmount) internal override returns (uint256[] memory assets) {
address[] memory tokens = pool.getTokens();
address depositableTokenAddress = address(depositableToken);
(uint256 amount0Desired, uint256 amount1Desired) = tokens[0] == depositableTokenAddress ? _divideToken0(depositAmount) : _divideToken1(depositAmount);
TransferHelper.safeApprove(address(tokens[0]), address(pool), amount0Desired);
TransferHelper.safeApprove(address(tokens[1]), address(pool), amount1Desired);
assets = new uint256[](4);
uint256[] memory tvl = totalValueLocked();
assets[2] = tvl[0];
assets[3] = tvl[1];
if (pool.getTokenId() == 0) {
(, , assets[0], assets[1]) = pool.mintNewPosition(amount0Desired, amount1Desired, _initialTickLower, _initialTickUpper, msg.sender);
}
else {
(, assets[0], assets[1]) = pool.increaseLiquidity(amount0Desired, amount1Desired, msg.sender);
}
}
return assets;
function _divideToken0(uint256 amountDepositTokenAsToken0) private returns (uint256 amount0, uint256 amount1) {
address[] memory tokens = pool.getTokens();
(amount0, ) = _splitFunds(amountDepositTokenAsToken0, true);
amount1 = _swap(address(depositableToken), tokens[1], amountDepositTokenAsToken0.sub(amount0));
}
function _divideToken1(uint256 amountDepositTokenAsToken1) private returns (uint256 amount0, uint256 amount1) {
address[] memory tokens = pool.getTokens();
(, amount1) = _splitFunds(amountDepositTokenAsToken1, false);
amount0 = _swap(address(depositableToken), tokens[0], amountDepositTokenAsToken1.sub(amount1));
}
function _splitFunds(uint256 funds, bool isFundToken0) private view returns (uint256 amount0, uint256 amount1) {
uint256 lowerPriceSqrtX96 = TickMath.getSqrtRatioAtTick(_initialTickLower);
uint256 upperPriceSqrtX96 = TickMath.getSqrtRatioAtTick(_initialTickUpper);
(amount0, amount1) = pool.splitFundsIntoTokens(lowerPriceSqrtX96, upperPriceSqrtX96, funds, isFundToken0);
require(amount0 > 0 && amount1 > 0, "Outside of price range");
}
function _processWithdrawAmount(uint256[] memory assets) internal override returns (uint256 withdrawAmount) {
return _withdrawAll(assets, false);
}
function _withdrawAll(uint256[] memory assets, bool chargeFee) internal returns (uint256 withdrawAmount) {
(uint256 amount0, uint256 amount1) = pool.decreaseLiquidity(uint128(assets[0]), 0, 0);
uint256 fee0 = 0;
uint256 fee1 = 0;
address[] memory tokens = pool.getTokens();
if (assets[1] != 0 || assets[2] != 0) {
(fee0, fee1) = pool.collect(address(this), uint128(assets[1]), uint128(assets[2]));
if (chargeFee) {
fee0 = fee0.sub(_chargeFee(IERC20(tokens[0]), 1, fee0));
fee1 = fee1.sub(_chargeFee(IERC20(tokens[1]), 1, fee1));
}
}
address depositableTokenAddress = address(depositableToken);
withdrawAmount += tokens[0] == depositableTokenAddress ? amount0 + fee0 : _swap(tokens[0], depositableTokenAddress, amount0 + fee0);
withdrawAmount += tokens[1] == depositableTokenAddress ? amount1 + fee1 : _swap(tokens[1], depositableTokenAddress, amount1 + fee1);
}
function _withdrawAll(uint256[] memory assets, bool chargeFee) internal returns (uint256 withdrawAmount) {
(uint256 amount0, uint256 amount1) = pool.decreaseLiquidity(uint128(assets[0]), 0, 0);
uint256 fee0 = 0;
uint256 fee1 = 0;
address[] memory tokens = pool.getTokens();
if (assets[1] != 0 || assets[2] != 0) {
(fee0, fee1) = pool.collect(address(this), uint128(assets[1]), uint128(assets[2]));
if (chargeFee) {
fee0 = fee0.sub(_chargeFee(IERC20(tokens[0]), 1, fee0));
fee1 = fee1.sub(_chargeFee(IERC20(tokens[1]), 1, fee1));
}
}
address depositableTokenAddress = address(depositableToken);
withdrawAmount += tokens[0] == depositableTokenAddress ? amount0 + fee0 : _swap(tokens[0], depositableTokenAddress, amount0 + fee0);
withdrawAmount += tokens[1] == depositableTokenAddress ? amount1 + fee1 : _swap(tokens[1], depositableTokenAddress, amount1 + fee1);
}
function _withdrawAll(uint256[] memory assets, bool chargeFee) internal returns (uint256 withdrawAmount) {
(uint256 amount0, uint256 amount1) = pool.decreaseLiquidity(uint128(assets[0]), 0, 0);
uint256 fee0 = 0;
uint256 fee1 = 0;
address[] memory tokens = pool.getTokens();
if (assets[1] != 0 || assets[2] != 0) {
(fee0, fee1) = pool.collect(address(this), uint128(assets[1]), uint128(assets[2]));
if (chargeFee) {
fee0 = fee0.sub(_chargeFee(IERC20(tokens[0]), 1, fee0));
fee1 = fee1.sub(_chargeFee(IERC20(tokens[1]), 1, fee1));
}
}
address depositableTokenAddress = address(depositableToken);
withdrawAmount += tokens[0] == depositableTokenAddress ? amount0 + fee0 : _swap(tokens[0], depositableTokenAddress, amount0 + fee0);
withdrawAmount += tokens[1] == depositableTokenAddress ? amount1 + fee1 : _swap(tokens[1], depositableTokenAddress, amount1 + fee1);
}
function _swap(address from, address to, uint256 amountIn) private returns (uint256 amountOut) {
TransferHelper.safeApprove(from, address(pool), amountIn);
amountOut = pool.swapExactInputSingle(IERC20(from), IERC20(to), amountIn);
}
function rebalance() public onlyRole(DEFAULT_ADMIN_ROLE) {
_pause();
uint256[] memory assets = new uint256[](3);
assets[0] = pool.getTotalLiquidity();
(assets[1], assets[2]) = pool.getFeesToCollect();
uint256 totalAmount = _withdrawAll(assets, true);
pool.resetPosition();
require(pool.getTokenId() == 0, "Position exists");
uint256 fee = _chargeFee(depositableToken, 0, totalAmount);
_processDepositAmount(totalAmount.sub(fee));
_unpause();
}
} | 16,303,203 | [
1,
20775,
14468,
33,
13491,
9190,
422,
20775,
1432,
12275,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
735,
71,
8230,
690,
14461,
12003,
353,
3155,
1235,
12003,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
16724,
9890,
10477,
364,
509,
5034,
31,
203,
565,
1450,
15038,
2148,
10477,
5664,
364,
2254,
5034,
31,
203,
203,
565,
1599,
2294,
2864,
2845,
31,
203,
565,
509,
3247,
3238,
389,
6769,
6264,
4070,
31,
203,
565,
509,
3247,
3238,
389,
6769,
6264,
5988,
31,
203,
203,
565,
3885,
12,
2867,
443,
2767,
2214,
1345,
67,
16,
1758,
302,
338,
2864,
1887,
67,
16,
509,
3247,
2172,
6264,
4070,
67,
16,
509,
3247,
2172,
6264,
5988,
67,
13,
7010,
3639,
3155,
1235,
12003,
12,
323,
2767,
2214,
1345,
67,
13,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
29,
31,
203,
565,
288,
203,
3639,
2845,
273,
1599,
2294,
2864,
12,
561,
2864,
1887,
67,
1769,
203,
203,
3639,
444,
4435,
16610,
12,
6769,
6264,
4070,
67,
16,
2172,
6264,
5988,
67,
1769,
203,
565,
289,
27699,
203,
565,
445,
444,
4435,
16610,
12,
474,
3247,
2172,
6264,
4070,
67,
16,
509,
3247,
2172,
6264,
5988,
67,
13,
1071,
1338,
2996,
12,
5280,
67,
15468,
67,
16256,
13,
288,
203,
3639,
389,
6769,
6264,
4070,
273,
2172,
6264,
4070,
67,
31,
203,
3639,
389,
6769,
6264,
5988,
273,
2172,
6264,
5988,
67,
31,
203,
565,
289,
203,
203,
565,
445,
444,
758,
1724,
429,
1345,
12,
2867,
389,
323,
1724,
429,
1345,
13,
203,
2
]
|
pragma solidity ^0.4.25;
contract NTA3DEvents {
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
event onBuyKey
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
uint256 roundID,
uint256 ethIn,
uint256 keys,
uint256 timeStamp
);
event onBuyCard
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
uint256 cardID,
uint256 ethIn,
uint256 timeStamp
);
event onRoundEnd
(
address winnerAddr,
bytes32 winnerName,
uint256 roundID,
uint256 amountWon,
uint256 newPot,
uint256 timeStamp
);
event onDrop
(
address dropwinner,
bytes32 winnerName,
uint256 roundID,
uint256 droptype, //0:smalldrop 1:bigdop
uint256 win,
uint256 timeStamp
);
}
contract NTA3D is NTA3DEvents {
using SafeMath for *;
using NameFilter for string;
using NTA3DKeysCalc for uint256;
string constant public name = "No Tricks Allow 3D";
string constant public symbol = "NTA3D";
bool activated_;
address admin;
uint256 constant private rndStarts = 12 hours; // ??need to be continue
uint256 constant private rndPerKey = 15 seconds; // every key increase seconds
uint256 constant private rndMax = 12 hours; //max count down time;
uint256 constant private cardValidity = 1 hours; //stock cards validity
uint256 constant private cardPrice = 0.05 ether; //stock cards validity
uint256 constant private DIVIDE = 1000; // common divide tool
uint256 constant private smallDropTrigger = 50 ether;
uint256 constant private bigDropTrigger = 300000 * 1e18;
uint256 constant private keyPriceTrigger = 50000 * 1e18;
uint256 constant private keyPriceFirst = 0.0005 ether;
uint256 constant private oneOffInvest1 = 0.1 ether;//VIP 1
uint256 constant private oneOffInvest2 = 1 ether;// VIP 2
//uint256 public airDropTracker_ = 0;
uint256 public rID; // round id number / total rounds that have happened
uint256 public pID; // total players
//player map data
mapping (address => uint256) public pIDxAddr; // get pid by address
mapping (bytes32 => uint256) public pIDxName; // get name by pid
mapping (uint256 => NTAdatasets.Player) public pIDPlayer; // get player struct by pid\
mapping (uint256 => mapping (uint256 => NTAdatasets.PlayerRound)) public pIDPlayerRound; // pid => rid => playeround
//stock cards
mapping (uint256 => NTAdatasets.Card) cIDCard; //get card by cID
address cardSeller;
//team map data
//address gameFundsAddr = 0xFD7A82437F7134a34654D7Cb8F79985Df72D7076;
address[11] partner;
address to06;
address to04;
address to20A;
address to20B;
mapping (address => uint256) private gameFunds; // game develeopment get 5% funds
//uint256 private teamFee; // team Fee 5%
//round data
mapping (uint256 => NTAdatasets.Round) public rIDRound; // round data
// team dividens
mapping (uint256 => NTAdatasets.Deposit) public deposit;
mapping (uint256 => NTAdatasets.PotSplit) public potSplit;
constructor() public {
//constructor
activated_ = false;
admin = msg.sender;
// Team allocation structures
// 0 = BISHOP
// 1 = ROOK
// BISHOP team: ==> |46% to all, 17% to winnerPot, 5% to develop funds, 5% to teamfee, 10% to cards,
// |7% to fisrt degree invatation
// |3% to second degree invatation, 2% to big airdrop, 5% to small airdrop
deposit[0] = NTAdatasets.Deposit(460, 170, 50, 50, 100, 100, 20, 50);
// ROOK team: ==> |20% to all, 43% to winnerPot, 5% to develop funds, 5% to teamfee, 10% to cards,
// |7% to fisrt degree invatation
// |3% to second degree invatation, 2% to big airdrop, 5% to small airdrop
deposit[1] = NTAdatasets.Deposit(200, 430, 50, 50, 100, 100, 20, 50);
// potSplit: ==> |20% to all, 45% to lastwinner, 5% to inviter 1st, 3% to inviter 2nd, 2% to inviter 3rd,
// |8% to key buyer 1st, 5% to key buyer 2nd, 2% to key buyer 3rd, 10% to next round
potSplit[0] = NTAdatasets.PotSplit(200, 450, 50, 30, 20, 80, 50, 20, 100);
potSplit[1] = NTAdatasets.PotSplit(200, 450, 50, 30, 20, 80, 50, 20, 100);
}
//==============================================================================
//
// safety checks
//==============================================================================
//tested
modifier isActivated() {
require(activated_ == true, "its not ready yet");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
//tested
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
//tested
modifier isAdmin() {require(msg.sender == admin, "its can only be call by admin");_;}
/**
* @dev sets boundaries for incoming tx
*/
//tested
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
//==============================================================================
//
// admin functions
//==============================================================================
//tested
function activeNTA() isAdmin() public {
activated_ = true;
partner[0] = 0xE27Aa5E7D8906779586CfB9DbA2935BDdd7c8210;
partner[1] = 0xD4638827Dc486cb59B5E5e47955059A160BaAE13;
partner[2] = 0xa088c667591e04cC78D6dfA3A392A132dc5A7f9d;
partner[3] = 0xed38deE26c751ff575d68D9Bf93C312e763f8F87;
partner[4] = 0x42A7B62f71b7778279DA2639ceb5DD6ee884f905;
partner[5] = 0xd471409F3eFE9Ca24b63855005B08D4548742a5b;
partner[6] = 0x41c9F005eD19C2B620152f5562D26029b32078B6;
partner[7] = 0x11b85bc860A6C38fa7fe6f54f18d350eF5f2787b;
partner[8] = 0x11a7c5E7887F2C34356925275882D4321a6B69A8;
partner[9] = 0xB5754c7bD005b6F25e1FDAA5f94b2b71e6eA260f;
partner[10] = 0x6fbC15cF6d0B05280E99f753E45B631815715E99;
to06 = 0x9B53CC857cD9DD5EbE6bc07Bde67D8CE4076345f;
to04 = 0x5835a72118c0C784203B8d39936A0875497B6eCa;
to20A = 0xEc2441D3113fC2376cd127344331c0F1b959Ce1C;
to20B = 0xd1Dac908c97c0a885e9B413a84ACcC0010C002d2;
//card
cardSeller = 0xeE4f032bdB0f9B51D6c7035d3DEFfc217D91225C;
}
//tested
function startFirstRound() isAdmin() isActivated() public {
//must not open before
require(rID == 0);
newRound(0);
}
function teamWithdraw() public
isHuman()
isActivated()
{
uint256 _temp;
address to = msg.sender;
require(gameFunds[to] != 0, "you dont have funds");
_temp = gameFunds[to];
gameFunds[to] = 0;
to.transfer(_temp);
}
function getTeamFee(address _addr)
public
view
returns(uint256) {
return gameFunds[_addr];
}
function getScore(address _addr)
public
view
isAdmin()
returns(uint256) {
uint256 _pID = pIDxAddr[_addr];
if(_pID == 0 ) return 0;
else return pIDPlayerRound[_pID][rID].score;
}
function setInviterCode(address _addr, uint256 _inv, uint256 _vip, string _nameString)
public
isAdmin() {
//this is for popularzing channel
bytes32 _name = _nameString.nameFilter();
uint256 temp = pIDxName[_name];
require(temp == 0, "name already regist");
uint256 _pID = pIDxAddr[_addr];
if(_pID == 0) {
pID++;
_pID = pID;
pIDxAddr[_addr] = _pID;
pIDPlayer[_pID].addr = _addr;
pIDPlayer[_pID].name = _name;
pIDxName[_name] = _pID;
pIDPlayer[_pID].inviter1 = _inv;
pIDPlayer[_pID].vip = _vip;
} else {
if(_inv != 0)
pIDPlayer[_pID].inviter1 = _inv;
pIDPlayer[_pID].name = _name;
pIDxName[_name] = _pID;
pIDPlayer[_pID].vip = _vip;
}
}
//==============================================================================
//
// player functions
//==============================================================================
//emergency buy uses BISHOP team to buy keys
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
//fetch player
require(rID != 0, "No round existed yet");
uint256 _pID = managePID(0);
//buy key
buyCore(_pID, 0);
}
// buy with ID: inviter use pID to invate player to buy like "www.NTA3D.io/?id=101"
function buyXid(uint256 _team,uint256 _inviter)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
require(rID != 0, "No round existed yet");
uint256 _pID = managePID(_inviter);
if (_team < 0 || _team > 1 ) {
_team = 0;
}
buyCore(_pID, _team);
}
// buy with ID: inviter use pID to invate player to buy like "www.NTA3D.io/?n=obama"
function buyXname(uint256 _team,string _invName)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
require(rID != 0, "No round existed yet");
bytes32 _name = _invName.nameFilter();
uint256 _invPID = pIDxName[_name];
uint256 _pID = managePID(_invPID);
if (_team < 0 || _team > 1 ) {
_team = 0;
}
buyCore(_pID, _team);
}
function buyCardXname(uint256 _cID, string _invName)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable {
uint256 _value = msg.value;
uint256 _now = now;
require(_cID < 20, "only has 20 cards");
require(_value == cardPrice, "the card cost 0.05 ether");
require(cIDCard[_cID].owner == 0 || (cIDCard[_cID].buyTime + cardValidity) < _now, "card is in used");
bytes32 _name = _invName.nameFilter();
uint256 _invPID = pIDxName[_name];
uint256 _pID = managePID(_invPID);
for (uint i = 0; i < 20; i++) {
require(_pID != cIDCard[i].owner, "you already registed a card");
}
gameFunds[cardSeller] = gameFunds[cardSeller].add(_value);
cIDCard[_cID].addr = msg.sender;
cIDCard[_cID].owner = _pID;
cIDCard[_cID].buyTime = _now;
cIDCard[_cID].earnings = 0;
emit onBuyCard(_pID, pIDPlayer[_pID].addr, pIDPlayer[_pID].name, _cID, _value, now);
}
function buyCardXid(uint256 _cID, uint256 _inviter)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable {
uint256 _value = msg.value;
uint256 _now = now;
require(_cID < 20, "only has 20 cards");
require(_value == cardPrice, "the card cost 0.05 ether");
require(cIDCard[_cID].owner == 0 || (cIDCard[_cID].buyTime + cardValidity) < _now, "card is in used");
uint256 _pID = managePID(_inviter);
for (uint i = 0; i < 20; i++) {
require(_pID != cIDCard[i].owner, "you already registed a card");
}
gameFunds[cardSeller] = gameFunds[cardSeller].add(_value);
cIDCard[_cID].addr = msg.sender;
cIDCard[_cID].owner = _pID;
cIDCard[_cID].buyTime = _now;
cIDCard[_cID].earnings = 0;
emit onBuyCard(_pID, pIDPlayer[_pID].addr, pIDPlayer[_pID].name, _cID, _value, now);
}
// regist a name
function registNameXid(string _nameString, uint256 _inviter)
isActivated()
isHuman()
public {
bytes32 _name = _nameString.nameFilter();
uint256 temp = pIDxName[_name];
require(temp == 0, "name already regist");
uint256 _pID = managePID(_inviter);
pIDxName[_name] = _pID;
pIDPlayer[_pID].name = _name;
}
function registNameXname(string _nameString, string _inviterName)
isActivated()
isHuman()
public {
bytes32 _name = _nameString.nameFilter();
uint256 temp = pIDxName[_name];
require(temp == 0, "name already regist");
bytes32 _invName = _inviterName.nameFilter();
uint256 _invPID = pIDxName[_invName];
uint256 _pID = managePID(_invPID);
pIDxName[_name] = _pID;
pIDPlayer[_pID].name = _name;
}
function withdraw()
isActivated()
isHuman()
public {
// setup local rID
uint256 _rID = rID;
// grab time
uint256 _now = now;
uint256 _pID = pIDxAddr[msg.sender];
require(_pID != 0, "cant find user");
uint256 _eth = 0;
if (rIDRound[_rID].end < _now && rIDRound[_rID].ended == false) {
rIDRound[_rID].ended = true;
endRound();
}
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
pIDPlayer[_pID].addr.transfer(_eth);
//emit
emit onWithdraw(_pID, pIDPlayer[_pID].addr, pIDPlayer[_pID].name, _eth, now);
}
//==============================================================================
//
// view functions
//==============================================================================
/**
* return the price buyer will pay for next 1 individual key.
* @return price for next key bought (in wei format)
*/
//tested
function getBuyPrice(uint256 _key)
public
view
returns(uint256) {
// setup local rID
uint256 _rID = rID;
// grab time
uint256 _now = now;
uint256 _keys = rIDRound[_rID].team1Keys + rIDRound[_rID].team2Keys;
// round is active
if (rIDRound[_rID].end >= _now || (rIDRound[_rID].end < _now && rIDRound[_rID].leadPID == 0))
return _keys.ethRec(_key * 1e18);
else
return keyPriceFirst;
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* @return time left in seconds
*/
//tested
function getTimeLeft()
public
view
returns(uint256) {
// setup local rID
uint256 _rID = rID;
// grab time
uint256 _now = now;
if (rIDRound[_rID].end >= _now)
return (rIDRound[_rID].end.sub(_now));
else
return 0;
}
//tested
function getPlayerVaults()
public
view
returns(uint256, uint256, uint256, uint256, uint256) {
// setup local rID
uint256 _rID = rID;
uint256 _now = now;
uint256 _pID = pIDxAddr[msg.sender];
if (_pID == 0)
return (0, 0, 0, 0, 0);
uint256 _last = pIDPlayer[_pID].lrnd;
uint256 _inv = pIDPlayerRound[_pID][_last].inv;
uint256 _invMask = pIDPlayerRound[_pID][_last].invMask;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (rIDRound[_rID].end < _now && rIDRound[_rID].ended == false && rIDRound[_rID].leadPID != 0) {
// if player is winner
if (rIDRound[_rID].leadPID == _pID)
return (
(pIDPlayer[_pID].win).add((rIDRound[_rID].pot).mul(45) / 100),
pIDPlayer[_pID].gen.add(calcUnMaskedEarnings(_pID, pIDPlayer[_pID].lrnd)),
pIDPlayer[_pID].inv.add(_inv).sub0(_invMask),
pIDPlayer[_pID].tim.add(calcTeamEarnings(_pID, pIDPlayer[_pID].lrnd)),
pIDPlayer[_pID].crd
);
else
return (
pIDPlayer[_pID].win,
pIDPlayer[_pID].gen.add(calcUnMaskedEarnings(_pID, pIDPlayer[_pID].lrnd)),
pIDPlayer[_pID].inv.add(_inv).sub0(_invMask),
pIDPlayer[_pID].tim.add(calcTeamEarnings(_pID, pIDPlayer[_pID].lrnd)),
pIDPlayer[_pID].crd
);
} else {
return (
pIDPlayer[_pID].win,
pIDPlayer[_pID].gen.add(calcUnMaskedEarnings(_pID, pIDPlayer[_pID].lrnd)),
pIDPlayer[_pID].inv.add(_inv).sub0(_invMask),
pIDPlayer[_pID].tim.add(calcTeamEarnings(_pID, pIDPlayer[_pID].lrnd)),
pIDPlayer[_pID].crd
);
}
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256) {
// setup local rID
uint256 _rID = rID;
return(_rID,
rIDRound[_rID].team1Keys + rIDRound[_rID].team2Keys, //total key
rIDRound[_rID].eth, //total eth
rIDRound[_rID].strt, //start time
rIDRound[_rID].end, //end time
rIDRound[_rID].pot, //last winer pot
rIDRound[_rID].leadPID, //current last player
pIDPlayer[rIDRound[_rID].leadPID].addr, //cureest last player address
pIDPlayer[rIDRound[_rID].leadPID].name, //cureest last player name
rIDRound[_rID].smallDrop,
rIDRound[_rID].bigDrop,
rIDRound[_rID].teamPot //teampot
);
}
function getRankList()
public
view
//invitetop3 amout keyTop3 key
returns (address[3], uint256[3], bytes32[3], address[3], uint256[3], bytes32[3]) {
uint256 _rID = rID;
address[3] memory inv;
address[3] memory key;
bytes32[3] memory invname;
uint256[3] memory invRef;
uint256[3] memory keyamt;
bytes32[3] memory keyname;
inv[0] = pIDPlayer[rIDRound[_rID].invTop3[0]].addr;
inv[1] = pIDPlayer[rIDRound[_rID].invTop3[1]].addr;
inv[2] = pIDPlayer[rIDRound[_rID].invTop3[2]].addr;
invRef[0] = pIDPlayerRound[rIDRound[_rID].invTop3[0]][_rID].inv;
invRef[1] = pIDPlayerRound[rIDRound[_rID].invTop3[1]][_rID].inv;
invRef[2] = pIDPlayerRound[rIDRound[_rID].invTop3[2]][_rID].inv;
invname[0] = pIDPlayer[rIDRound[_rID].invTop3[0]].name;
invname[1] = pIDPlayer[rIDRound[_rID].invTop3[1]].name;
invname[2] = pIDPlayer[rIDRound[_rID].invTop3[2]].name;
key[0] = pIDPlayer[rIDRound[_rID].keyTop3[0]].addr;
key[1] = pIDPlayer[rIDRound[_rID].keyTop3[1]].addr;
key[2] = pIDPlayer[rIDRound[_rID].keyTop3[2]].addr;
keyamt[0] = pIDPlayerRound[rIDRound[_rID].keyTop3[0]][_rID].team1Keys + pIDPlayerRound[rIDRound[_rID].keyTop3[0]][_rID].team2Keys;
keyamt[1] = pIDPlayerRound[rIDRound[_rID].keyTop3[1]][_rID].team1Keys + pIDPlayerRound[rIDRound[_rID].keyTop3[1]][_rID].team2Keys;
keyamt[2] = pIDPlayerRound[rIDRound[_rID].keyTop3[2]][_rID].team1Keys + pIDPlayerRound[rIDRound[_rID].keyTop3[2]][_rID].team2Keys;
keyname[0] = pIDPlayer[rIDRound[_rID].keyTop3[0]].name;
keyname[1] = pIDPlayer[rIDRound[_rID].keyTop3[1]].name;
keyname[2] = pIDPlayer[rIDRound[_rID].keyTop3[2]].name;
return (inv, invRef, invname, key, keyamt, keyname);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
//tested
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr[_addr];
if (_pID == 0)
return (0, 0x0, 0, 0, 0);
else
return
(
_pID, //0
pIDPlayer[_pID].name, //1
pIDPlayerRound[_pID][_rID].team1Keys + pIDPlayerRound[_pID][_rID].team2Keys,
pIDPlayerRound[_pID][_rID].eth, //6
pIDPlayer[_pID].vip
);
}
function getCards(uint256 _id)
public
view
returns(uint256, address, bytes32, uint256, uint256) {
bytes32 _name = pIDPlayer[cIDCard[_id].owner].name;
return (
cIDCard[_id].owner,
cIDCard[_id].addr,
_name,
cIDCard[_id].buyTime,
cIDCard[_id].earnings
);
}
//==============================================================================
//
// private functions
//==============================================================================
//tested
function managePID(uint256 _inviter) private returns(uint256) {
uint256 _pID = pIDxAddr[msg.sender];
if (_pID == 0) {
pID++;
pIDxAddr[msg.sender] = pID;
pIDPlayer[pID].addr = msg.sender;
pIDPlayer[pID].name = 0x0;
_pID = pID;
}
// handle direct and second hand inviter
if (pIDPlayer[_pID].inviter1 == 0 && pIDPlayer[_inviter].addr != address(0) && _pID != _inviter) {
pIDPlayer[_pID].inviter1 = _inviter;
uint256 _in = pIDPlayer[_inviter].inviter1;
if (_in != 0) {
pIDPlayer[_pID].inviter2 = _in;
}
}
// oneoff invite get invitation link
if (msg.value >= oneOffInvest2) {
pIDPlayer[_pID].vip = 2;
} else if (msg.value >= oneOffInvest1) {
if (pIDPlayer[_pID].vip != 2)
pIDPlayer[_pID].vip = 1;
}
return _pID;
}
function buyCore(uint256 _pID, uint256 _team) private {
// setup local rID
uint256 _rID = rID;
// grab time
uint256 _now = now;
//update last round;
if (pIDPlayer[_pID].lrnd != _rID)
updateVault(_pID);
pIDPlayer[_pID].lrnd = _rID;
uint256 _inv1 = pIDPlayer[_pID].inviter1;
uint256 _inv2 = pIDPlayer[_pID].inviter2;
// round is active
if (rIDRound[_rID].end >= _now || (rIDRound[_rID].end < _now && rIDRound[_rID].leadPID == 0)) {
core(_rID, _pID, msg.value, _team);
if (_inv1 != 0)
doRankInv(_rID, _inv1, rIDRound[_rID].invTop3, pIDPlayerRound[_inv1][_rID].inv);
if (_inv2 != 0)
doRankInv(_rID, _inv2, rIDRound[_rID].invTop3, pIDPlayerRound[_inv2][_rID].inv);
doRankKey(_rID, _pID, rIDRound[_rID].keyTop3, pIDPlayerRound[_pID][_rID].team1Keys + pIDPlayerRound[_pID][_rID].team2Keys);
emit onBuyKey(
_pID,
pIDPlayer[_pID].addr,
pIDPlayer[_pID].name, _rID,
msg.value,
pIDPlayerRound[_pID][_rID].team1Keys + pIDPlayerRound[_pID][_rID].team2Keys,
now);
} else {
if (rIDRound[_rID].end < _now && rIDRound[_rID].ended == false) {
rIDRound[_rID].ended = true;
endRound();
//if you trigger the endround. whatever how much you pay ,you will fail to buykey
//and the eth will return to your gen.
pIDPlayer[_pID].gen = pIDPlayer[_pID].gen.add(msg.value);
}
}
}
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team) private {
NTAdatasets.Round storage _roundID = rIDRound[_rID];
NTAdatasets.Deposit storage _deposit = deposit[_team];
//NTAdatasets.PlayerRound storage _playerRound = pIDPlayerRound[_pID][_rID];
// calculate how many keys they can get
uint256 _keysAll = _roundID.team1Keys + _roundID.team2Keys;//(rIDRound[_rID].eth).keysRec(_eth);
uint256 _keys = _keysAll.keysRec(rIDRound[_rID].eth + _eth);
if (_keys >= 1000000000000000000) {
updateTimer(_keys, _rID);
}
uint256 _left = _eth;
//2% to bigDrop
uint256 _temp = _eth.mul(_deposit.bigDrop) / DIVIDE;
doBigDrop(_rID, _pID, _keys, _temp);
_left = _left.sub0(_temp);
//5% to smallDrop
_temp = _eth.mul(_deposit.smallDrop) / DIVIDE;
doSmallDrop(_rID, _pID, _eth, _temp);
_left = _left.sub0(_temp);
_roundID.eth = _roundID.eth.add(_eth);
pIDPlayerRound[_pID][_rID].eth = pIDPlayerRound[_pID][_rID].eth.add(_eth);
if (_team == 0) {
_roundID.team1Keys = _roundID.team1Keys.add(_keys);
pIDPlayerRound[_pID][_rID].team1Keys = pIDPlayerRound[_pID][_rID].team1Keys.add(_keys);
} else {
_roundID.team2Keys = _roundID.team2Keys.add(_keys);
pIDPlayerRound[_pID][_rID].team2Keys = pIDPlayerRound[_pID][_rID].team2Keys.add(_keys);
}
//X% to all
uint256 _all = _eth.mul(_deposit.allPlayer) / DIVIDE;
_roundID.playerPot = _roundID.playerPot.add(_all);
uint256 _dust = updateMasks(_rID, _pID, _all, _keys);
_roundID.pot = _roundID.pot.add(_dust);
_left = _left.sub0(_all);
//X% to winnerPot
_temp = _eth.mul(_deposit.pot) / DIVIDE;
_roundID.pot = _roundID.pot.add(_temp);
_left = _left.sub0(_temp);
//5% to develop funds
_temp = _eth.mul(_deposit.devfunds) / DIVIDE;
doDevelopFunds(_temp);
//gameFunds[gameFundsAddr] = gameFunds[gameFundsAddr].add(_temp);
_left = _left.sub0(_temp);
//5% to team fee
_temp = _eth.mul(_deposit.teamFee) / DIVIDE;
//gameFunds[partner1] = gameFunds[partner1].add(_temp.mul(50) / DIVIDE);
_dust = doPartnerShares(_temp);
_left = _left.sub0(_temp).add(_dust);
//10% to cards
_temp = _eth.mul(_deposit.cards) / DIVIDE;
_left = _left.sub0(_temp).add(distributeCards(_temp));
// if no cards ,the money will add into left
// 10% to invatation
_temp = _eth.mul(_deposit.inviter) / DIVIDE;
_dust = doInvite(_rID, _pID, _temp);
_left = _left.sub0(_temp).add(_dust);
//update round;
if (_keys >= 1000000000000000000) {
_roundID.leadPID = _pID;
_roundID.team = _team;
}
_roundID.smallDrop = _roundID.smallDrop.add(_left);
}
//tested
function doInvite(uint256 _rID, uint256 _pID, uint256 _value) private returns(uint256){
uint256 _score = msg.value;
uint256 _left = _value;
uint256 _inviter1 = pIDPlayer[_pID].inviter1;
uint256 _fee;
uint256 _inviter2 = pIDPlayer[_pID].inviter2;
if (_inviter1 != 0)
pIDPlayerRound[_inviter1][_rID].score = pIDPlayerRound[_inviter1][_rID].score.add(_score);
if (_inviter2 != 0)
pIDPlayerRound[_inviter2][_rID].score = pIDPlayerRound[_inviter2][_rID].score.add(_score);
//invitor
if (_inviter1 == 0 || pIDPlayer[_inviter1].vip == 0)
return _left;
if (pIDPlayer[_inviter1].vip == 1) {
_fee = _value.mul(70) / 100;
_inviter2 = pIDPlayer[_pID].inviter2;
_left = _left.sub0(_fee);
pIDPlayerRound[_inviter1][_rID].inv = pIDPlayerRound[_inviter1][_rID].inv.add(_fee);
if (_inviter2 == 0 || pIDPlayer[_inviter2].vip != 2)
return _left;
else {
_fee = _value.mul(30) / 100;
_left = _left.sub0(_fee);
pIDPlayerRound[_inviter2][_rID].inv = pIDPlayerRound[_inviter2][_rID].inv.add(_fee);
return _left;
}
} else if (pIDPlayer[_inviter1].vip == 2) {
_left = _left.sub0(_value);
pIDPlayerRound[_inviter1][_rID].inv = pIDPlayerRound[_inviter1][_rID].inv.add(_value);
return _left;
} else {
return _left;
}
}
function doRankInv(uint256 _rID, uint256 _pID, uint256[3] storage rank, uint256 _value) private {
if (_value >= pIDPlayerRound[rank[0]][_rID].inv && _value != 0) {
if (_pID != rank[0]) {
uint256 temp = rank[0];
rank[0] = _pID;
if (rank[1] == _pID) {
rank[1] = temp;
} else {
rank[2] = rank[1];
rank[1] = temp;
}
}
} else if (_value >= pIDPlayerRound[rank[1]][_rID].inv && _value != 0) {
if (_pID != rank[1]) {
rank[2] = rank[1];
rank[1] = _pID;
}
} else if (_value >= pIDPlayerRound[rank[2]][_rID].inv && _value != 0) {
rank[2] = _pID;
}
}
function doRankKey(uint256 _rID, uint256 _pID, uint256[3] storage rank, uint256 _value) private {
if (_value >= (pIDPlayerRound[rank[0]][_rID].team1Keys + pIDPlayerRound[rank[0]][_rID].team2Keys)) {
if (_pID != rank[0]) {
uint256 temp = rank[0];
rank[0] = _pID;
if (rank[1] == _pID) {
rank[1] = temp;
} else {
rank[2] = rank[1];
rank[1] = temp;
}
}
} else if (_value >= (pIDPlayerRound[rank[1]][_rID].team1Keys + pIDPlayerRound[rank[1]][_rID].team2Keys)) {
if (_pID != rank[1]){
rank[2] = rank[1];
rank[1] = _pID;
}
} else if (_value >= (pIDPlayerRound[rank[2]][_rID].team1Keys + pIDPlayerRound[rank[2]][_rID].team2Keys)) {
rank[2] = _pID;
}
}
//tested
function doSmallDrop(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _small) private {
// modulo current round eth, and add player eth to see if it can trigger the trigger;
uint256 _remain = rIDRound[_rID].eth % smallDropTrigger;
if ((_remain + _eth) >= smallDropTrigger) {
uint256 _reward = rIDRound[_rID].smallDrop;
rIDRound[_rID].smallDrop = 0;
pIDPlayer[_pID].win = pIDPlayer[_pID].win.add(_reward);
rIDRound[_rID].smallDrop = rIDRound[_rID].smallDrop.add(_small);
emit NTA3DEvents.onDrop(pIDPlayer[_pID].addr, pIDPlayer[_pID].name, _rID, 0, _reward, now);
//emit
} else {
rIDRound[_rID].smallDrop = rIDRound[_rID].smallDrop.add(_small);
}
}
//tested
function doBigDrop(uint256 _rID, uint256 _pID, uint256 _key, uint256 _big) private {
uint256 _keys = rIDRound[_rID].team1Keys + rIDRound[_rID].team2Keys;
uint256 _remain = _keys % bigDropTrigger;
if ((_remain + _key) >= bigDropTrigger) {
uint256 _reward = rIDRound[_rID].bigDrop;
rIDRound[_rID].bigDrop = 0;
pIDPlayer[_pID].win = pIDPlayer[_pID].win.add(_reward);
rIDRound[_rID].bigDrop = rIDRound[_rID].bigDrop.add(_big);
emit NTA3DEvents.onDrop(pIDPlayer[_pID].addr, pIDPlayer[_pID].name, _rID, 1, _reward, now);
//emit
} else {
rIDRound[_rID].bigDrop = rIDRound[_rID].bigDrop.add(_big);
}
}
function distributeCards(uint256 _eth) private returns(uint256){
uint256 _each = _eth / 20;
uint256 _remain = _eth;
for (uint i = 0; i < 20; i++) {
uint256 _pID = cIDCard[i].owner;
if (_pID != 0) {
pIDPlayer[_pID].crd = pIDPlayer[_pID].crd.add(_each);
cIDCard[i].earnings = cIDCard[i].earnings.add(_each);
_remain = _remain.sub0(_each);
}
}
return _remain;
}
function doPartnerShares(uint256 _eth) private returns(uint256) {
uint i;
uint256 _temp;
uint256 _left = _eth;
//first 10%
_temp = _eth.mul(10) / 100;
gameFunds[partner[0]] = gameFunds[partner[0]].add(_temp);
for(i = 1; i < 11; i++) {
_temp = _eth.mul(9) / 100;
gameFunds[partner[i]] = gameFunds[partner[i]].add(_temp);
_left = _left.sub0(_temp);
}
return _left;
}
function doDevelopFunds(uint256 _eth) private{
uint256 _temp;
_temp = _eth.mul(12) / 100;
gameFunds[to06] = gameFunds[to06].add(_temp);
_temp = _eth.mul(8) / 100;
gameFunds[to04] = gameFunds[to04].add(_temp);
_temp = _eth.mul(40) / 100;
gameFunds[to20A] = gameFunds[to20A].add(_temp);
_temp = _eth.mul(40) / 100;
gameFunds[to20B] = gameFunds[to20B].add(_temp);
}
function endRound() private {
NTAdatasets.Round storage _roundID = rIDRound[rID];
NTAdatasets.PotSplit storage _potSplit = potSplit[0];
uint256 _winPID = _roundID.leadPID;
uint256 _pot = _roundID.pot;
uint256 _left = _pot;
//the pot is too small endround will ignore the dividens
//new round will start at 0 eth
if(_pot < 10000000000000) {
emit onRoundEnd(pIDPlayer[_winPID].addr, pIDPlayer[_winPID].name, rID, _roundID.pot,0, now);
newRound(0);
return;
}
// potSplit: ==> |20% to all, 45% to lastwinner, 5% to inviter 1st, 3% to inviter 2nd, 2% to inviter 3rd,
// |8% to key buyer 1st, 5% to key buyer 2nd, 2% to key buyer 3rd, 10% to next round
//20% to all
uint256 _all = _pot.mul(_potSplit.allPlayer) / DIVIDE;
_roundID.teamPot = _roundID.teamPot.add(_all);
_left = _left.sub0(_all);
//45% to lastwinner
uint256 _temp = _pot.mul(_potSplit.lastWinner) / DIVIDE;
pIDPlayer[_winPID].win = pIDPlayer[_winPID].win.add(_temp);
_left = _left.sub0(_temp);
//5% to inviter 1st, 3% to inviter 2nd, 2% to inviter 3rd
uint256 _inv1st = _pot.mul(_potSplit.inviter1st) / DIVIDE;
if (_roundID.invTop3[0] != 0) {
pIDPlayer[_roundID.invTop3[0]].win = pIDPlayer[_roundID.invTop3[0]].win.add(_inv1st);
_left = _left.sub0(_inv1st);
}
_inv1st = _pot.mul(_potSplit.inviter2nd) / DIVIDE;
if (_roundID.invTop3[1] != 0) {
pIDPlayer[_roundID.invTop3[1]].win = pIDPlayer[_roundID.invTop3[1]].win.add(_inv1st);
_left = _left.sub0(_inv1st);
}
_inv1st = _pot.mul(_potSplit.inviter3rd) / DIVIDE;
if (_roundID.invTop3[2] != 0) {
pIDPlayer[_roundID.invTop3[2]].win = pIDPlayer[_roundID.invTop3[2]].win.add(_inv1st);
_left = _left.sub0(_inv1st);
}
//8% to key buyer 1st, 5% to key buyer 2nd, 2% to key buyer 3rd
_inv1st = _pot.mul(_potSplit.key1st) / DIVIDE;
if (_roundID.keyTop3[0] != 0) {
pIDPlayer[_roundID.keyTop3[0]].win = pIDPlayer[_roundID.keyTop3[0]].win.add(_inv1st);
_left = _left.sub0(_inv1st);
}
_inv1st = _pot.mul(_potSplit.key2nd) / DIVIDE;
if (_roundID.keyTop3[1] != 0) {
pIDPlayer[_roundID.keyTop3[1]].win = pIDPlayer[_roundID.keyTop3[1]].win.add(_inv1st);
_left = _left.sub0(_inv1st);
}
_inv1st = _pot.mul(_potSplit.key3rd) / DIVIDE;
if (_roundID.keyTop3[2] != 0) {
pIDPlayer[_roundID.keyTop3[2]].win = pIDPlayer[_roundID.keyTop3[2]].win.add(_inv1st);
_left = _left.sub0(_inv1st);
}
//10% to next round
uint256 _newPot = _pot.mul(potSplit[0].next) / DIVIDE;
_left = _left.sub0(_newPot);
emit onRoundEnd(pIDPlayer[_winPID].addr, pIDPlayer[_winPID].name, rID, _roundID.pot, _newPot + _left, now);
//start new round
newRound(_newPot + _left);
}
//tested
function newRound(uint256 _eth) private {
if (rIDRound[rID].ended == true || rID == 0) {
rID++;
rIDRound[rID].strt = now;
rIDRound[rID].end = now.add(rndMax);
rIDRound[rID].pot = rIDRound[rID].pot.add(_eth);
}
}
function updateMasks(uint256 _rID, uint256 _pID, uint256 _all, uint256 _keys) private
returns(uint256) {
//calculate average share of each new eth in
uint256 _allKeys = rIDRound[_rID].team1Keys + rIDRound[_rID].team2Keys;
uint256 _unit = _all.mul(1000000000000000000) / _allKeys;
rIDRound[_rID].mask = rIDRound[_rID].mask.add(_unit);
//calculate this round player can get
uint256 _share = (_unit.mul(_keys)) / (1000000000000000000);
pIDPlayerRound[_pID][_rID].mask = pIDPlayerRound[_pID][_rID].mask.add((rIDRound[_rID].mask.mul(_keys) / (1000000000000000000)).sub(_share));
return(_all.sub(_unit.mul(_allKeys) / (1000000000000000000)));
}
function withdrawEarnings(uint256 _pID) private returns(uint256) {
updateVault(_pID);
uint256 earnings = (pIDPlayer[_pID].win).add(pIDPlayer[_pID].gen).add(pIDPlayer[_pID].inv).add(pIDPlayer[_pID].tim).add(pIDPlayer[_pID].crd);
if (earnings > 0) {
pIDPlayer[_pID].win = 0;
pIDPlayer[_pID].gen = 0;
pIDPlayer[_pID].inv = 0;
pIDPlayer[_pID].tim = 0;
pIDPlayer[_pID].crd = 0;
}
return earnings;
}
function updateVault(uint256 _pID) private {
uint256 _rID = pIDPlayer[_pID].lrnd;
updateGenVault(_pID, _rID);
updateInvVault(_pID, _rID);
uint256 _team = calcTeamEarnings(_pID, _rID);
//already calculate team reward,ended round key and mask dont needed
if(rIDRound[_rID].ended == true) {
pIDPlayerRound[_pID][_rID].team1Keys = 0;
pIDPlayerRound[_pID][_rID].team2Keys = 0;
pIDPlayerRound[_pID][_rID].mask = 0;
}
pIDPlayer[_pID].tim = pIDPlayer[_pID].tim.add(_team);
}
function updateGenVault(uint256 _pID, uint256 _rID) private {
uint256 _earnings = calcUnMaskedEarnings(_pID, _rID);
//put invitation reward to gen
if (_earnings > 0) {
// put in gen vault
pIDPlayer[_pID].gen = _earnings.add(pIDPlayer[_pID].gen);
// zero out their earnings by updating mask
pIDPlayerRound[_pID][_rID].mask = _earnings.add(pIDPlayerRound[_pID][_rID].mask);
}
}
function updateInvVault(uint256 _pID, uint256 _rID) private {
uint256 _inv = pIDPlayerRound[_pID][_rID].inv;
uint256 _invMask = pIDPlayerRound[_pID][_rID].invMask;
if (_inv > 0) {
pIDPlayer[_pID].inv = pIDPlayer[_pID].inv.add(_inv).sub0(_invMask);
pIDPlayerRound[_pID][_rID].invMask = pIDPlayerRound[_pID][_rID].invMask.add(_inv).sub0(_invMask);
}
}
//calculate valut not update
function calcUnMaskedEarnings(uint256 _pID, uint256 _rID) private view
returns (uint256)
{
uint256 _all = pIDPlayerRound[_pID][_rID].team1Keys + pIDPlayerRound[_pID][_rID].team2Keys;
return ((rIDRound[_rID].mask.mul(_all)) / (1000000000000000000)).sub(pIDPlayerRound[_pID][_rID].mask);
}
function calcTeamEarnings(uint256 _pID, uint256 _rID) private view
returns (uint256)
{
uint256 _key1 = pIDPlayerRound[_pID][_rID].team1Keys;
uint256 _key2 = pIDPlayerRound[_pID][_rID].team2Keys;
if (rIDRound[_rID].ended == false)
return 0;
else {
if (rIDRound[_rID].team == 0)
return rIDRound[_rID].teamPot.mul(_key1 / rIDRound[_rID].team1Keys);
else
return rIDRound[_rID].teamPot.mul(_key2 / rIDRound[_rID].team2Keys);
}
}
//tested
function updateTimer(uint256 _keys, uint256 _rID) private {
// grab time
uint256 _now = now;
// calculate new time
uint256 _newTime;
if (_now > rIDRound[_rID].end && rIDRound[_rID].leadPID == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndPerKey)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndPerKey)).add(rIDRound[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax).add(_now))
rIDRound[_rID].end = _newTime;
else
rIDRound[_rID].end = rndMax.add(_now);
}
}
library NTA3DKeysCalc {
using SafeMath for *;
uint256 constant private keyPriceTrigger = 50000 * 1e18;
uint256 constant private keyPriceFirst = 0.0005 ether;
uint256 constant private keyPriceAdd = 0.0001 ether;
/**
* @dev calculates number of keys received given X eth
* _curEth current amount of eth in contract
* _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curKeys, uint256 _allEth)
internal
pure
returns (uint256)
{
return(keys(_curKeys, _allEth));
}
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return(eth(_sellKeys.add(_curKeys)).sub(eth(_curKeys)));
}
function keys(uint256 _keys, uint256 _eth)
internal
pure
returns(uint256)
{
uint256 _times = _keys / keyPriceTrigger;
uint i = 0;
uint256 eth1;
uint256 eth2;
uint256 price;
uint256 key2;
for(i = _times;i < i + 200; i++) {
if(eth(keyPriceTrigger * (i + 1)) >= _eth) {
if(i == 0) eth1 = 0;
else eth1 = eth(keyPriceTrigger * i);
eth2 = _eth.sub(eth1);
price = i.mul(keyPriceAdd).add(keyPriceFirst);
key2 = (eth2 / price).mul(1e18);
return ((keyPriceTrigger * i + key2).sub0(_keys));
break;
}
}
//too large
require(false, "too large eth in");
}
//tested
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
uint256 _times = _keys / keyPriceTrigger;//keyPriceTrigger;
uint256 _remain = _keys % keyPriceTrigger;//keyPriceTrigger;
uint256 _price = _times.mul(keyPriceAdd).add(keyPriceFirst);
if (_times == 0) {
return (keyPriceFirst.mul(_keys / 1e18));
} else {
uint256 _up = (_price.sub(keyPriceFirst)).mul(_remain / 1e18);
uint256 _down = (_keys / 1e18).mul(keyPriceFirst);
uint256 _add = (_times.mul(_times).sub(_times) / 2).mul(keyPriceAdd).mul(keyPriceTrigger / 1e18);
return (_up + _down + _add);
}
}
}
library NTAdatasets {
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 inv; // inviter vault
uint256 tim; //team pot
uint256 crd; //crd pot
uint256 lrnd; // last round played
uint256 inviter1; // direct inviter
uint256 inviter2; // second hand inviter
uint256 vip; //0 no vip; 1 and 2
}
struct PlayerRound {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 team1Keys;
uint256 team2Keys;
uint256 inv;
uint256 mask;
uint256 invMask;
uint256 score;
}
struct Round {
uint256 leadPID; // pID of player in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 team1Keys; // keys
uint256 team2Keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth win pot
uint256 team;
uint256 teamPot;
uint256 smallDrop;//50Eth airdrop
uint256 bigDrop; //300000 eth airdrop
uint256 playerPot;
uint256 mask;
uint256[3] invTop3;
uint256[3] keyTop3;
}
struct Card {
uint256 owner; //pID of card owner
address addr;
uint256 buyTime; //validity time check
uint256 earnings;
}
struct Deposit {
uint256 allPlayer; // all player this rounds by key
uint256 pot; // last winner pot
uint256 devfunds; // game development Pot
uint256 teamFee; // team fee
uint256 cards; // stock right cards
uint256 inviter;
uint256 bigDrop;
uint256 smallDrop;
}
struct PotSplit {
uint256 allPlayer; // all player this rounds by key
uint256 lastWinner; // final player
uint256 inviter1st; // player who get 1st of invatation
uint256 inviter2nd;
uint256 inviter3rd;
uint256 key1st; // player who get 1st key amount
uint256 key2nd;
uint256 key3rd;
uint256 next; // next round
}
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Subtracts two numbers, no throw
*/
function sub0(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a < b) {
return 0;
} else {
return a - b;
}
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | pID of player in lead
| uint256 leadPID; | 1,788,987 | [
1,
84,
734,
434,
7291,
316,
5871,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2254,
5034,
5871,
16522,
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,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xc153eeAD19e0DBbDb3462Dcc2B703cC6D738A37c/sources/KyberNetworkProxy.sol | @notice Backward compatible function @notice Use token address ETH_TOKEN_ADDRESS for ether @dev Trade from src to dest token and sends dest token to destAddress @param src Source token @param srcAmount Amount of src tokens in twei @param dest Destination token @param destAddress Address to send tokens to @param maxDestAmount A limit on the amount of dest tokens in twei @param minConversionRate The minimal conversion rate. If actual rate is lower, trade reverts @param walletId Platform wallet address for receiving fees @param hint Advanced instructions for running the trade @return Amount of actual dest tokens in twei | function tradeWithHint(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address payable destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address payable walletId,
bytes calldata hint
) external payable override returns (uint256) {
return
doTrade(
src,
srcAmount,
dest,
destAddress,
maxDestAmount,
minConversionRate,
walletId,
0,
hint
);
}
| 2,711,866 | [
1,
26283,
7318,
445,
225,
2672,
1147,
1758,
512,
2455,
67,
8412,
67,
15140,
364,
225,
2437,
225,
2197,
323,
628,
1705,
358,
1570,
1147,
471,
9573,
1570,
1147,
358,
1570,
1887,
225,
1705,
4998,
1147,
225,
1705,
6275,
16811,
434,
1705,
2430,
316,
10810,
77,
225,
1570,
10691,
1147,
225,
1570,
1887,
5267,
358,
1366,
2430,
358,
225,
943,
9378,
6275,
432,
1800,
603,
326,
3844,
434,
1570,
2430,
316,
10810,
77,
225,
1131,
6814,
4727,
1021,
16745,
4105,
4993,
18,
971,
3214,
4993,
353,
2612,
16,
18542,
15226,
87,
225,
9230,
548,
11810,
9230,
1758,
364,
15847,
1656,
281,
225,
7380,
27451,
12509,
364,
3549,
326,
18542,
327,
16811,
434,
3214,
1570,
2430,
316,
10810,
77,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
18542,
1190,
7002,
12,
203,
3639,
4232,
39,
3462,
1705,
16,
203,
3639,
2254,
5034,
1705,
6275,
16,
203,
3639,
4232,
39,
3462,
1570,
16,
203,
3639,
1758,
8843,
429,
1570,
1887,
16,
203,
3639,
2254,
5034,
943,
9378,
6275,
16,
203,
3639,
2254,
5034,
1131,
6814,
4727,
16,
203,
3639,
1758,
8843,
429,
9230,
548,
16,
203,
3639,
1731,
745,
892,
7380,
203,
565,
262,
3903,
8843,
429,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
203,
5411,
741,
22583,
12,
203,
7734,
1705,
16,
203,
7734,
1705,
6275,
16,
203,
7734,
1570,
16,
203,
7734,
1570,
1887,
16,
203,
7734,
943,
9378,
6275,
16,
203,
7734,
1131,
6814,
4727,
16,
203,
7734,
9230,
548,
16,
203,
7734,
374,
16,
203,
7734,
7380,
203,
5411,
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
]
|
./full_match/13337/0x9c895367323b67e63F7a76E9A5228AfAd307d364/sources/project:/contracts/pools/xphoton/XPhotonStaking.sol | Universal variables | contract XPhotonStaking is NonblockingLzApp, Ownable2Step, ReentrancyGuard, AccessControl {
using SafeERC20 for IERC20;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
uint8 public constant ACTION_STAKE = 1;
uint256 public constant RST_REWARD_DECIMALS = 10000000000000;
IERC20 public rainiStudioToken;
uint256 public totalSupply;
pragma solidity ^0.8.9;
struct GeneralRewardVars {
uint32 lastUpdateTime;
uint32 periodFinish;
uint128 rstRewardPerTokenStored;
uint128 rstRewardRate;
}
GeneralRewardVars public generalRewardVars;
struct AccountRewardVars {
uint32 lastUpdated;
uint96 rstRewards;
uint128 rstRewardPerTokenPaid;
}
struct AccountVars {
uint256 staked;
}
mapping(address => AccountRewardVars) internal accountRewardVars;
mapping(address => AccountVars) internal accountVars;
event TokensStaked(address payer, uint256 amount, uint256 timestamp);
event RewardWithdrawn(address owner, uint256 amount, uint256 timestamp);
event RewardPoolAdded(
uint256 _amount,
uint256 _duration,
uint256 timestamp
);
constructor(
address _rainiStudioToken,
address _lzEndpoint
) NonblockingLzApp(_lzEndpoint) {
require(
_rainiStudioToken != address(0),
"XPhotonStaking: _rainiStudioToken is zero address"
);
rainiStudioToken = IERC20(_rainiStudioToken);
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
modifier onlyMinter() {
require(hasRole(MINTER_ROLE, _msgSender()), "caller is not a minter");
_;
}
function withdrawReward() external nonReentrant {
_balanceUpdate(_msgSender());
uint256 reward = rstEarned(_msgSender());
require(reward > 1, "no reward to withdraw");
if (reward > 1) {
accountRewardVars[_msgSender()].rstRewards = 0;
rainiStudioToken.safeTransfer(_msgSender(), reward);
}
emit RewardWithdrawn(_msgSender(), reward, block.timestamp);
}
function withdrawReward() external nonReentrant {
_balanceUpdate(_msgSender());
uint256 reward = rstEarned(_msgSender());
require(reward > 1, "no reward to withdraw");
if (reward > 1) {
accountRewardVars[_msgSender()].rstRewards = 0;
rainiStudioToken.safeTransfer(_msgSender(), reward);
}
emit RewardWithdrawn(_msgSender(), reward, block.timestamp);
}
function getStaked(address _owner) public view returns (uint256) {
return accountVars[_owner].staked;
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, generalRewardVars.periodFinish);
}
function rstRewardPerToken() public view returns (uint256) {
GeneralRewardVars memory _generalRewardVars = generalRewardVars;
if (totalSupply == 0) {
return _generalRewardVars.rstRewardPerTokenStored;
}
return
_generalRewardVars.rstRewardPerTokenStored +
(uint256(
lastTimeRewardApplicable() - _generalRewardVars.lastUpdateTime
) *
_generalRewardVars.rstRewardRate *
RST_REWARD_DECIMALS) /
totalSupply;
}
function rstRewardPerToken() public view returns (uint256) {
GeneralRewardVars memory _generalRewardVars = generalRewardVars;
if (totalSupply == 0) {
return _generalRewardVars.rstRewardPerTokenStored;
}
return
_generalRewardVars.rstRewardPerTokenStored +
(uint256(
lastTimeRewardApplicable() - _generalRewardVars.lastUpdateTime
) *
_generalRewardVars.rstRewardRate *
RST_REWARD_DECIMALS) /
totalSupply;
}
function rstEarned(address account) public view returns (uint256) {
AccountRewardVars memory _accountRewardVars = accountRewardVars[
account
];
AccountVars memory _accountVars = accountVars[account];
uint256 calculatedEarned = (uint256(_accountVars.staked) *
(rstRewardPerToken() - _accountRewardVars.rstRewardPerTokenPaid)) /
RST_REWARD_DECIMALS +
_accountRewardVars.rstRewards;
uint256 poolBalance = rainiStudioToken.balanceOf(address(this));
if (calculatedEarned > poolBalance) return poolBalance;
return calculatedEarned;
}
function addRstRewardPool(
uint256 _amount,
uint256 _duration
) external onlyOwner nonReentrant {
_balanceUpdate(address(0));
GeneralRewardVars memory _generalRewardVars = generalRewardVars;
if (_generalRewardVars.periodFinish > block.timestamp) {
uint256 timeRemaining = _generalRewardVars.periodFinish -
block.timestamp;
_amount += timeRemaining * _generalRewardVars.rstRewardRate;
}
rainiStudioToken.safeTransferFrom(_msgSender(), address(this), _amount);
_generalRewardVars.rstRewardRate = uint128(_amount / _duration);
_generalRewardVars.periodFinish = uint32(block.timestamp + _duration);
_generalRewardVars.lastUpdateTime = uint32(block.timestamp);
generalRewardVars = _generalRewardVars;
emit RewardPoolAdded(_amount, _duration, block.timestamp);
}
function addRstRewardPool(
uint256 _amount,
uint256 _duration
) external onlyOwner nonReentrant {
_balanceUpdate(address(0));
GeneralRewardVars memory _generalRewardVars = generalRewardVars;
if (_generalRewardVars.periodFinish > block.timestamp) {
uint256 timeRemaining = _generalRewardVars.periodFinish -
block.timestamp;
_amount += timeRemaining * _generalRewardVars.rstRewardRate;
}
rainiStudioToken.safeTransferFrom(_msgSender(), address(this), _amount);
_generalRewardVars.rstRewardRate = uint128(_amount / _duration);
_generalRewardVars.periodFinish = uint32(block.timestamp + _duration);
_generalRewardVars.lastUpdateTime = uint32(block.timestamp);
generalRewardVars = _generalRewardVars;
emit RewardPoolAdded(_amount, _duration, block.timestamp);
}
function abortRstRewardPool() external onlyOwner nonReentrant {
_balanceUpdate(address(0));
GeneralRewardVars memory _generalRewardVars = generalRewardVars;
require(
_generalRewardVars.periodFinish > block.timestamp,
"Reward pool is not active"
);
uint256 timeRemaining = _generalRewardVars.periodFinish -
block.timestamp;
uint256 remainingAmount = timeRemaining *
_generalRewardVars.rstRewardRate;
rainiStudioToken.transfer(_msgSender(), remainingAmount);
_generalRewardVars.rstRewardRate = 0;
_generalRewardVars.periodFinish = uint32(block.timestamp);
_generalRewardVars.lastUpdateTime = uint32(block.timestamp);
generalRewardVars = _generalRewardVars;
}
function recoverRst(uint256 _amount) external onlyOwner nonReentrant {
require(
generalRewardVars.periodFinish < block.timestamp,
"rst cannot be recovered while reward pool active."
);
rainiStudioToken.transfer(_msgSender(), _amount);
}
function bulkStake(address[] memory _users, uint256[] memory _amounts)
external
onlyOwner
{
require(_users.length == _amounts.length, "XPhotonStaking: Wrong array length");
for (uint256 i = 0; i < _users.length; i++) {
_stake(_users[i], _amounts[i]);
}
}
function bulkStake(address[] memory _users, uint256[] memory _amounts)
external
onlyOwner
{
require(_users.length == _amounts.length, "XPhotonStaking: Wrong array length");
for (uint256 i = 0; i < _users.length; i++) {
_stake(_users[i], _amounts[i]);
}
}
function mint(
address _to,
uint256 _amount
) external onlyMinter {
_stake(_to, _amount);
}
function _nonblockingLzReceive(
uint16,
bytes memory,
uint64,
bytes memory _payload
) internal override {
(address user, uint8 action, uint256 amount) = abi.decode(
_payload,
(address, uint8, uint256)
);
require(action == ACTION_STAKE, "XPhotonStaking: Wrong L0 Action");
_stake(user, amount);
}
function _stake(address _user, uint256 _amount) internal {
totalSupply = totalSupply + _amount;
uint256 currentStake = accountVars[_user].staked;
accountVars[_user].staked = currentStake + _amount;
emit TokensStaked(_user, _amount, block.timestamp);
}
function _balanceUpdate(address _owner) internal {
AccountRewardVars memory _accountRewardVars = accountRewardVars[_owner];
AccountVars memory _accountVars = accountVars[_owner];
GeneralRewardVars memory _generalRewardVars = generalRewardVars;
_generalRewardVars.rstRewardPerTokenStored = uint64(
rstRewardPerToken()
);
_generalRewardVars.lastUpdateTime = uint32(lastTimeRewardApplicable());
if (_owner != address(0)) {
_accountRewardVars.lastUpdated = uint32(block.timestamp);
_accountRewardVars.rstRewards = uint96(rstEarned(_owner));
_accountRewardVars.rstRewardPerTokenPaid = _generalRewardVars
.rstRewardPerTokenStored;
}
accountRewardVars[_owner] = _accountRewardVars;
accountVars[_owner] = _accountVars;
generalRewardVars = _generalRewardVars;
}
function _balanceUpdate(address _owner) internal {
AccountRewardVars memory _accountRewardVars = accountRewardVars[_owner];
AccountVars memory _accountVars = accountVars[_owner];
GeneralRewardVars memory _generalRewardVars = generalRewardVars;
_generalRewardVars.rstRewardPerTokenStored = uint64(
rstRewardPerToken()
);
_generalRewardVars.lastUpdateTime = uint32(lastTimeRewardApplicable());
if (_owner != address(0)) {
_accountRewardVars.lastUpdated = uint32(block.timestamp);
_accountRewardVars.rstRewards = uint96(rstEarned(_owner));
_accountRewardVars.rstRewardPerTokenPaid = _generalRewardVars
.rstRewardPerTokenStored;
}
accountRewardVars[_owner] = _accountRewardVars;
accountVars[_owner] = _accountVars;
generalRewardVars = _generalRewardVars;
}
function transferOwnership(
address newOwner
) public override(Ownable, Ownable2Step) onlyOwner {
Ownable2Step.transferOwnership(newOwner);
}
function _transferOwnership(
address newOwner
) internal override(Ownable, Ownable2Step) {
Ownable2Step._transferOwnership(newOwner);
}
}
| 13,236,376 | [
1,
984,
14651,
3152,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
1139,
3731,
352,
265,
510,
6159,
353,
3858,
18926,
48,
94,
3371,
16,
14223,
6914,
22,
4160,
16,
868,
8230,
12514,
16709,
16,
24349,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
565,
1731,
1578,
1071,
5381,
6989,
2560,
67,
16256,
273,
417,
24410,
581,
5034,
2932,
6236,
2560,
67,
16256,
8863,
203,
203,
565,
2254,
28,
1071,
5381,
11385,
67,
882,
37,
6859,
273,
404,
31,
203,
565,
2254,
5034,
1071,
5381,
534,
882,
67,
862,
21343,
67,
23816,
55,
273,
2130,
12648,
3784,
31,
203,
203,
565,
467,
654,
39,
3462,
1071,
767,
8767,
510,
4484,
1345,
31,
203,
203,
565,
2254,
5034,
1071,
2078,
3088,
1283,
31,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
29,
31,
203,
203,
565,
1958,
9544,
17631,
1060,
5555,
288,
203,
3639,
2254,
1578,
1142,
1891,
950,
31,
203,
3639,
2254,
1578,
3879,
11641,
31,
203,
3639,
2254,
10392,
13978,
17631,
1060,
2173,
1345,
18005,
31,
203,
3639,
2254,
10392,
13978,
17631,
1060,
4727,
31,
203,
565,
289,
203,
203,
565,
9544,
17631,
1060,
5555,
1071,
7470,
17631,
1060,
5555,
31,
203,
203,
203,
565,
1958,
6590,
17631,
1060,
5555,
288,
203,
3639,
2254,
1578,
1142,
7381,
31,
203,
3639,
2254,
10525,
13978,
17631,
14727,
31,
203,
3639,
2254,
10392,
13978,
17631,
1060,
2173,
1345,
16507,
350,
31,
203,
565,
289,
203,
203,
565,
1958,
6590,
5555,
288,
203,
3639,
2254,
5034,
384,
9477,
31,
203,
565,
289,
203,
203,
565,
2874,
12,
2
]
|
./partial_match/1/0xB02b25158d0875de0A9084eC85768133f97A9828/sources/src/Cassette.sol | * @notice Override `ONFT1155Core` function to debit a batch of tokens from the current chain @param _from Address to debit tokens from @param _tokenIds Tokens to debit @param _amounts Amounts of tokens to debit/ | function _debitFrom(
address _from,
uint256[] memory _tokenIds,
uint256[] memory _amounts
)
internal
override
{
if (msg.sender != _from && !isApprovedForAll(_from, msg.sender)) revert Cassette_NotAllowed();
_batchBurn(_from, _from, _tokenIds, _amounts);
}
| 9,352,348 | [
1,
6618,
1375,
673,
4464,
2499,
2539,
4670,
68,
445,
358,
443,
3682,
279,
2581,
434,
2430,
628,
326,
783,
2687,
225,
389,
2080,
5267,
358,
443,
3682,
2430,
628,
225,
389,
2316,
2673,
13899,
358,
443,
3682,
225,
389,
8949,
87,
16811,
87,
434,
2430,
358,
443,
3682,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
323,
3682,
1265,
12,
203,
3639,
1758,
389,
2080,
16,
203,
3639,
2254,
5034,
8526,
3778,
389,
2316,
2673,
16,
203,
3639,
2254,
5034,
8526,
3778,
389,
8949,
87,
203,
565,
262,
203,
3639,
2713,
203,
3639,
3849,
203,
565,
288,
203,
3639,
309,
261,
3576,
18,
15330,
480,
389,
2080,
597,
401,
291,
31639,
1290,
1595,
24899,
2080,
16,
1234,
18,
15330,
3719,
15226,
385,
428,
7637,
67,
19354,
5621,
203,
203,
3639,
389,
5303,
38,
321,
24899,
2080,
16,
389,
2080,
16,
389,
2316,
2673,
16,
389,
8949,
87,
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
]
|
./full_match/1/0xf9231D28B34CD77A08542f73ca87c4411B1b8B56/sources/vesper-strategies/contracts/strategies/Strategy.sol | @notice Claim rewardToken and convert rewardToken into collateral token. | function claimAndSwapRewards(uint256 _minAmountOut) external onlyKeeper returns (uint256 _amountOut) {
uint256 _collateralBefore = collateralToken.balanceOf(address(this));
_claimAndSwapRewards();
_amountOut = collateralToken.balanceOf(address(this)) - _collateralBefore;
require(_amountOut >= _minAmountOut, "not-enough-amountOut");
}
| 4,930,754 | [
1,
9762,
19890,
1345,
471,
1765,
19890,
1345,
1368,
4508,
2045,
287,
1147,
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,
7516,
1876,
12521,
17631,
14727,
12,
11890,
5034,
389,
1154,
6275,
1182,
13,
3903,
1338,
17891,
1135,
261,
11890,
5034,
389,
8949,
1182,
13,
288,
203,
3639,
2254,
5034,
389,
12910,
2045,
287,
4649,
273,
4508,
2045,
287,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
389,
14784,
1876,
12521,
17631,
14727,
5621,
203,
3639,
389,
8949,
1182,
273,
4508,
2045,
287,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
300,
389,
12910,
2045,
287,
4649,
31,
203,
3639,
2583,
24899,
8949,
1182,
1545,
389,
1154,
6275,
1182,
16,
315,
902,
17,
275,
4966,
17,
8949,
1182,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x43998b23BfbB946950cd70be88D7bFba7686912b/sources/Users/akshaycm/Documents/rfits-token/contracts/abstractions/Balancer.sol | Sell half of the amount to ETHSwap half of it to ethSend part of it to treasuryAdd liq with remaining eth and tokens | function AddLiq() external {
uint256 befETHBalance = address(this).balance;
uint256 tokenAmount = token.balanceOf(address(this));
swapTokensForETH(tokenAmount.div(2));
require(txSuccess,"treasury send fail");
uint256 ethDiff = address(this).balance.sub(befETHBalance);
addLiq(token.balanceOf(address(this)),ethDiff);
}
| 673,236 | [
1,
55,
1165,
8816,
434,
326,
3844,
358,
512,
2455,
12521,
8816,
434,
518,
358,
13750,
3826,
1087,
434,
518,
358,
9787,
345,
22498,
986,
4501,
85,
598,
4463,
13750,
471,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1436,
48,
18638,
1435,
3903,
288,
203,
3639,
2254,
5034,
506,
74,
1584,
44,
13937,
273,
1758,
12,
2211,
2934,
12296,
31,
203,
3639,
2254,
5034,
1147,
6275,
225,
273,
1147,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
7720,
5157,
1290,
1584,
44,
12,
2316,
6275,
18,
2892,
12,
22,
10019,
203,
3639,
2583,
12,
978,
4510,
10837,
27427,
345,
22498,
1366,
2321,
8863,
203,
3639,
2254,
5034,
13750,
5938,
273,
1758,
12,
2211,
2934,
12296,
18,
1717,
12,
2196,
74,
1584,
44,
13937,
1769,
203,
3639,
527,
48,
18638,
12,
2316,
18,
12296,
951,
12,
2867,
12,
2211,
13,
3631,
546,
5938,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
/*
* @title ERC721 token for Goon bods
*/
contract GoonBods is ERC721Enumerable, ERC721Burnable, Ownable {
string private baseTokenURI;
AvatarContract goonContract;
mapping(uint256 => uint256) mintedTraitAmount;
mapping(uint256 => bool) usedGoons;
mapping(uint256 => Body) bodies;
// array length is total number of traits
uint256[158] public scarcities = [
250, 100, 1500, 600, 250, 250, 600, 10, 600, 75, 1500, 1500,
100, 400, 400, 400, 400, 50, 75, 75, 150, 800, 1000, 100,
1000, 1000, 600, 200, 1000, 250, 100, 250, 200, 1500, 75, 400,
600, 500, 300, 25, 800, 500, 600, 200, 300, 1500, 300, 1500,
600, 10, 1000, 1500, 150, 400, 400, 250, 100, 1000, 600, 600,
1500, 1500, 300, 150, 1500, 1500, 1500, 500, 800, 500, 1000, 1000,
400, 600, 150, 250, 150, 1000, 75, 250, 150, 300, 10, 100,
600, 100, 800, 150, 800, 250, 500, 25, 50, 50, 1000, 150,
200, 200, 500, 300, 200, 1500, 1000, 50, 500, 800, 800, 50,
400, 500, 150, 500, 800, 10, 1000, 250, 150, 500, 250, 100,
800, 200, 100, 800, 75, 75, 25, 800, 400, 200, 600, 300,
150, 1500, 200, 10, 800, 300, 1500, 800, 500, 300, 100, 1000,
75, 75, 200, 400, 1000, 100, 100, 1500, 100, 300, 300, 100,
25, 25
];
uint256 public constant MAX_BOTTOM_ID = 30;
uint256 public constant MAX_FOOTWEAR_ID = 59;
uint256 public constant MAX_BELT_ID = 88;
uint256 public constant MAX_WEAPON_ID = 120;
uint256 public constant MAX_ACCESSORY_ID = 157;
uint256 constant NO_TRAIT = 255;
event BodyMinted(address indexed _to, uint256 indexed _tokenId, uint256 indexed _goonId, uint8 _bottom, uint8 _footwear, uint8 _belt, uint8 _leftHand, uint8 _rightHand);
struct Body {
uint8 bottom;
uint8 footwear;
uint8 belt;
uint8 leftHand;
uint8 rightHand;
}
constructor (
string memory _name,
string memory _symbol,
string memory _baseTokenURI,
address _goonContract
) ERC721(_name, _symbol) {
baseTokenURI = _baseTokenURI;
goonContract = AvatarContract(_goonContract);
}
function setBaseURI(string memory _baseTokenURI) external onlyOwner {
baseTokenURI = _baseTokenURI;
}
function mint(uint8 _bottom, uint8 _footwear, uint8 _belt, uint8 _leftHand, uint8 _rightHand, uint256 goonID) external payable {
require(goonContract.ownerOf(goonID) == msg.sender, "Mint: Avatar not owned by sender");
require(!usedGoons[goonID], "Mint: Goon already used");
require((_bottom <= MAX_BOTTOM_ID || _bottom == NO_TRAIT) &&
((MAX_BOTTOM_ID <_footwear && _footwear <= MAX_FOOTWEAR_ID) || _footwear == NO_TRAIT) &&
((MAX_FOOTWEAR_ID <_belt && _belt <= MAX_BELT_ID) || _belt == NO_TRAIT) &&
((MAX_BELT_ID <_leftHand && _leftHand <= MAX_WEAPON_ID) || _leftHand == NO_TRAIT) &&
((MAX_WEAPON_ID <_rightHand && _rightHand <= MAX_ACCESSORY_ID) || _rightHand == NO_TRAIT),
"Mint: At least one trait id out of range");
require(_bottom != NO_TRAIT || _footwear != NO_TRAIT || _belt != NO_TRAIT || _leftHand != NO_TRAIT || _rightHand != NO_TRAIT, "Mint: At least one trait needs to be selected");
require(msg.value == getBodyPrice(_bottom, _footwear, _belt, _leftHand, _rightHand), "Mint: payment incorrect");
require(isTraitAvailable(_bottom) && isTraitAvailable(_footwear) && isTraitAvailable(_belt) && isTraitAvailable(_leftHand) && isTraitAvailable(_rightHand), "Mint: At least one trait sold out");
Body memory body = Body(_bottom, _footwear, _belt, _leftHand, _rightHand);
uint256 tokenId = totalSupply() + 1;
bodies[tokenId] = body;
if(_bottom != NO_TRAIT) mintedTraitAmount[_bottom] += 1;
if(_footwear != NO_TRAIT) mintedTraitAmount[_footwear] += 1;
if(_belt != NO_TRAIT) mintedTraitAmount[_belt] += 1;
if(_leftHand != NO_TRAIT) mintedTraitAmount[_leftHand] += 1;
if(_rightHand != NO_TRAIT) mintedTraitAmount[_rightHand] += 1;
usedGoons[goonID] = true;
_mint(msg.sender, tokenId);
emit BodyMinted(msg.sender, tokenId, goonID, _bottom, _footwear, _belt, _leftHand, _rightHand);
}
function withdrawEther(address payable _to, uint256 _amount) external onlyOwner {
_to.transfer(_amount);
}
function isTraitAvailable(uint traitId) public view returns (bool) {
return traitId == NO_TRAIT || mintedTraitAmount[traitId] < scarcities[traitId];
}
function getTraitAvailability() public view returns (bool[] memory){
bool[] memory result = new bool[](scarcities.length);
for(uint256 i; i < scarcities.length; i++) {
result[i] = isTraitAvailable(i);
}
return result;
}
function getUnusedAvatarsByOwner(address owner) public view returns (uint256[] memory) {
uint256[] memory tokens = goonContract.tokensOfOwner(owner);
uint256 numUnused = 0;
uint256[] memory result = new uint256[](tokens.length);
for(uint256 i; i < tokens.length; i++) {
if(!usedGoons[tokens[i]]) {
result[numUnused] = tokens[i];
numUnused++;
}
}
return trim(result, numUnused);
}
function getUnusedAvatars() public view returns (uint256[] memory) {
uint256 numUnused = 0;
uint256[] memory result = new uint256[](9696);
for(uint256 i=1; i <= 9696; i++) {
if(!usedGoons[i]) {
result[numUnused] = i;
numUnused++;
}
}
return trim(result, numUnused);
}
function trim(uint256[] memory result, uint256 numUnused) internal pure returns (uint256[] memory) {
uint256[] memory trimmedResult = new uint256[](numUnused);
for(uint256 i; i < numUnused; i++) {
trimmedResult[i] = result[i];
}
return trimmedResult;
}
function getMintedTraitAmounts() public view returns (uint256[] memory) {
uint256[] memory result = new uint[](MAX_ACCESSORY_ID);
for(uint256 i = 0; i < MAX_ACCESSORY_ID; i++) {
result[i] = mintedTraitAmount[i];
}
return result;
}
function getTraits(uint256 tokenId) public view returns (uint256[] memory) {
uint256[] memory result = new uint[](5);
result[0] = bodies[tokenId].bottom;
result[1] = bodies[tokenId].footwear;
result[2] = bodies[tokenId].belt;
result[3] = bodies[tokenId].leftHand;
result[4] = bodies[tokenId].rightHand;
return result;
}
function getBodyPrice(uint8 _bottom, uint8 _footwear, uint8 _belt, uint8 _leftHand, uint8 _rightHand) public view returns (uint256) {
return getTraitPrice(_bottom) + getTraitPrice(_footwear) + getTraitPrice(_belt) + getTraitPrice(_leftHand) + getTraitPrice(_rightHand);
}
function getTraitPrice(uint256 trait) public view returns (uint256) {
if(trait == NO_TRAIT || scarcities[trait] > 100) return 0;
uint256 scarcity = scarcities[trait];
if(scarcity > 75) return 69000000000000000;
if(scarcity > 50) return 99000000000000000;
if(scarcity > 25) return 190000000000000000;
if(scarcity > 10) return 390000000000000000;
return 690000000000000000;
}
function tokensOfOwner(address _owner) external view returns(uint256[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function _baseURI() internal view override returns (string memory) {
return baseTokenURI;
}
}
interface AvatarContract is IERC721 {
function tokensOfOwner(address owner) external view returns (uint256[] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "../../../utils/Context.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
} | @title ERC721 token for Goon bods/ array length is total number of traits | contract GoonBods is ERC721Enumerable, ERC721Burnable, Ownable {
string private baseTokenURI;
AvatarContract goonContract;
mapping(uint256 => uint256) mintedTraitAmount;
mapping(uint256 => bool) usedGoons;
mapping(uint256 => Body) bodies;
uint256[158] public scarcities = [
250, 100, 1500, 600, 250, 250, 600, 10, 600, 75, 1500, 1500,
100, 400, 400, 400, 400, 50, 75, 75, 150, 800, 1000, 100,
1000, 1000, 600, 200, 1000, 250, 100, 250, 200, 1500, 75, 400,
600, 500, 300, 25, 800, 500, 600, 200, 300, 1500, 300, 1500,
600, 10, 1000, 1500, 150, 400, 400, 250, 100, 1000, 600, 600,
1500, 1500, 300, 150, 1500, 1500, 1500, 500, 800, 500, 1000, 1000,
400, 600, 150, 250, 150, 1000, 75, 250, 150, 300, 10, 100,
600, 100, 800, 150, 800, 250, 500, 25, 50, 50, 1000, 150,
200, 200, 500, 300, 200, 1500, 1000, 50, 500, 800, 800, 50,
400, 500, 150, 500, 800, 10, 1000, 250, 150, 500, 250, 100,
800, 200, 100, 800, 75, 75, 25, 800, 400, 200, 600, 300,
150, 1500, 200, 10, 800, 300, 1500, 800, 500, 300, 100, 1000,
75, 75, 200, 400, 1000, 100, 100, 1500, 100, 300, 300, 100,
25, 25
];
uint256 public constant MAX_BOTTOM_ID = 30;
uint256 public constant MAX_FOOTWEAR_ID = 59;
uint256 public constant MAX_BELT_ID = 88;
uint256 public constant MAX_WEAPON_ID = 120;
uint256 public constant MAX_ACCESSORY_ID = 157;
uint256 constant NO_TRAIT = 255;
event BodyMinted(address indexed _to, uint256 indexed _tokenId, uint256 indexed _goonId, uint8 _bottom, uint8 _footwear, uint8 _belt, uint8 _leftHand, uint8 _rightHand);
pragma solidity ^0.8.4;
struct Body {
uint8 bottom;
uint8 footwear;
uint8 belt;
uint8 leftHand;
uint8 rightHand;
}
constructor (
string memory _name,
string memory _symbol,
string memory _baseTokenURI,
address _goonContract
) ERC721(_name, _symbol) {
baseTokenURI = _baseTokenURI;
goonContract = AvatarContract(_goonContract);
}
function setBaseURI(string memory _baseTokenURI) external onlyOwner {
baseTokenURI = _baseTokenURI;
}
function mint(uint8 _bottom, uint8 _footwear, uint8 _belt, uint8 _leftHand, uint8 _rightHand, uint256 goonID) external payable {
require(goonContract.ownerOf(goonID) == msg.sender, "Mint: Avatar not owned by sender");
require(!usedGoons[goonID], "Mint: Goon already used");
require((_bottom <= MAX_BOTTOM_ID || _bottom == NO_TRAIT) &&
((MAX_BOTTOM_ID <_footwear && _footwear <= MAX_FOOTWEAR_ID) || _footwear == NO_TRAIT) &&
((MAX_FOOTWEAR_ID <_belt && _belt <= MAX_BELT_ID) || _belt == NO_TRAIT) &&
((MAX_BELT_ID <_leftHand && _leftHand <= MAX_WEAPON_ID) || _leftHand == NO_TRAIT) &&
((MAX_WEAPON_ID <_rightHand && _rightHand <= MAX_ACCESSORY_ID) || _rightHand == NO_TRAIT),
"Mint: At least one trait id out of range");
require(_bottom != NO_TRAIT || _footwear != NO_TRAIT || _belt != NO_TRAIT || _leftHand != NO_TRAIT || _rightHand != NO_TRAIT, "Mint: At least one trait needs to be selected");
require(msg.value == getBodyPrice(_bottom, _footwear, _belt, _leftHand, _rightHand), "Mint: payment incorrect");
require(isTraitAvailable(_bottom) && isTraitAvailable(_footwear) && isTraitAvailable(_belt) && isTraitAvailable(_leftHand) && isTraitAvailable(_rightHand), "Mint: At least one trait sold out");
Body memory body = Body(_bottom, _footwear, _belt, _leftHand, _rightHand);
uint256 tokenId = totalSupply() + 1;
bodies[tokenId] = body;
if(_bottom != NO_TRAIT) mintedTraitAmount[_bottom] += 1;
if(_footwear != NO_TRAIT) mintedTraitAmount[_footwear] += 1;
if(_belt != NO_TRAIT) mintedTraitAmount[_belt] += 1;
if(_leftHand != NO_TRAIT) mintedTraitAmount[_leftHand] += 1;
if(_rightHand != NO_TRAIT) mintedTraitAmount[_rightHand] += 1;
usedGoons[goonID] = true;
_mint(msg.sender, tokenId);
emit BodyMinted(msg.sender, tokenId, goonID, _bottom, _footwear, _belt, _leftHand, _rightHand);
}
function withdrawEther(address payable _to, uint256 _amount) external onlyOwner {
_to.transfer(_amount);
}
function isTraitAvailable(uint traitId) public view returns (bool) {
return traitId == NO_TRAIT || mintedTraitAmount[traitId] < scarcities[traitId];
}
function getTraitAvailability() public view returns (bool[] memory){
bool[] memory result = new bool[](scarcities.length);
for(uint256 i; i < scarcities.length; i++) {
result[i] = isTraitAvailable(i);
}
return result;
}
function getTraitAvailability() public view returns (bool[] memory){
bool[] memory result = new bool[](scarcities.length);
for(uint256 i; i < scarcities.length; i++) {
result[i] = isTraitAvailable(i);
}
return result;
}
function getUnusedAvatarsByOwner(address owner) public view returns (uint256[] memory) {
uint256[] memory tokens = goonContract.tokensOfOwner(owner);
uint256 numUnused = 0;
uint256[] memory result = new uint256[](tokens.length);
for(uint256 i; i < tokens.length; i++) {
if(!usedGoons[tokens[i]]) {
result[numUnused] = tokens[i];
numUnused++;
}
}
return trim(result, numUnused);
}
function getUnusedAvatarsByOwner(address owner) public view returns (uint256[] memory) {
uint256[] memory tokens = goonContract.tokensOfOwner(owner);
uint256 numUnused = 0;
uint256[] memory result = new uint256[](tokens.length);
for(uint256 i; i < tokens.length; i++) {
if(!usedGoons[tokens[i]]) {
result[numUnused] = tokens[i];
numUnused++;
}
}
return trim(result, numUnused);
}
function getUnusedAvatarsByOwner(address owner) public view returns (uint256[] memory) {
uint256[] memory tokens = goonContract.tokensOfOwner(owner);
uint256 numUnused = 0;
uint256[] memory result = new uint256[](tokens.length);
for(uint256 i; i < tokens.length; i++) {
if(!usedGoons[tokens[i]]) {
result[numUnused] = tokens[i];
numUnused++;
}
}
return trim(result, numUnused);
}
function getUnusedAvatars() public view returns (uint256[] memory) {
uint256 numUnused = 0;
uint256[] memory result = new uint256[](9696);
for(uint256 i=1; i <= 9696; i++) {
if(!usedGoons[i]) {
result[numUnused] = i;
numUnused++;
}
}
return trim(result, numUnused);
}
function getUnusedAvatars() public view returns (uint256[] memory) {
uint256 numUnused = 0;
uint256[] memory result = new uint256[](9696);
for(uint256 i=1; i <= 9696; i++) {
if(!usedGoons[i]) {
result[numUnused] = i;
numUnused++;
}
}
return trim(result, numUnused);
}
function getUnusedAvatars() public view returns (uint256[] memory) {
uint256 numUnused = 0;
uint256[] memory result = new uint256[](9696);
for(uint256 i=1; i <= 9696; i++) {
if(!usedGoons[i]) {
result[numUnused] = i;
numUnused++;
}
}
return trim(result, numUnused);
}
function trim(uint256[] memory result, uint256 numUnused) internal pure returns (uint256[] memory) {
uint256[] memory trimmedResult = new uint256[](numUnused);
for(uint256 i; i < numUnused; i++) {
trimmedResult[i] = result[i];
}
return trimmedResult;
}
function trim(uint256[] memory result, uint256 numUnused) internal pure returns (uint256[] memory) {
uint256[] memory trimmedResult = new uint256[](numUnused);
for(uint256 i; i < numUnused; i++) {
trimmedResult[i] = result[i];
}
return trimmedResult;
}
function getMintedTraitAmounts() public view returns (uint256[] memory) {
uint256[] memory result = new uint[](MAX_ACCESSORY_ID);
for(uint256 i = 0; i < MAX_ACCESSORY_ID; i++) {
result[i] = mintedTraitAmount[i];
}
return result;
}
function getMintedTraitAmounts() public view returns (uint256[] memory) {
uint256[] memory result = new uint[](MAX_ACCESSORY_ID);
for(uint256 i = 0; i < MAX_ACCESSORY_ID; i++) {
result[i] = mintedTraitAmount[i];
}
return result;
}
function getTraits(uint256 tokenId) public view returns (uint256[] memory) {
uint256[] memory result = new uint[](5);
result[0] = bodies[tokenId].bottom;
result[1] = bodies[tokenId].footwear;
result[2] = bodies[tokenId].belt;
result[3] = bodies[tokenId].leftHand;
result[4] = bodies[tokenId].rightHand;
return result;
}
function getBodyPrice(uint8 _bottom, uint8 _footwear, uint8 _belt, uint8 _leftHand, uint8 _rightHand) public view returns (uint256) {
return getTraitPrice(_bottom) + getTraitPrice(_footwear) + getTraitPrice(_belt) + getTraitPrice(_leftHand) + getTraitPrice(_rightHand);
}
function getTraitPrice(uint256 trait) public view returns (uint256) {
if(trait == NO_TRAIT || scarcities[trait] > 100) return 0;
uint256 scarcity = scarcities[trait];
if(scarcity > 75) return 69000000000000000;
if(scarcity > 50) return 99000000000000000;
if(scarcity > 25) return 190000000000000000;
if(scarcity > 10) return 390000000000000000;
return 690000000000000000;
}
function tokensOfOwner(address _owner) external view returns(uint256[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
function tokensOfOwner(address _owner) external view returns(uint256[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
} else {
function tokensOfOwner(address _owner) external view returns(uint256[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function _baseURI() internal view override returns (string memory) {
return baseTokenURI;
}
}
| 10,086,703 | [
1,
654,
39,
27,
5340,
1147,
364,
4220,
265,
324,
369,
87,
19,
526,
769,
353,
2078,
1300,
434,
18370,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
4220,
265,
38,
369,
87,
353,
4232,
39,
27,
5340,
3572,
25121,
16,
4232,
39,
27,
5340,
38,
321,
429,
16,
14223,
6914,
288,
203,
565,
533,
3238,
1026,
1345,
3098,
31,
203,
203,
565,
8789,
8761,
8924,
1960,
265,
8924,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
2254,
5034,
13,
312,
474,
329,
15525,
6275,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
1426,
13,
1399,
5741,
7008,
31,
203,
565,
2874,
12,
11890,
5034,
516,
5652,
13,
25126,
31,
203,
203,
565,
2254,
5034,
63,
25984,
65,
1071,
888,
11828,
1961,
273,
306,
203,
4202,
16927,
16,
225,
2130,
16,
4711,
713,
16,
225,
14707,
16,
225,
16927,
16,
225,
16927,
16,
225,
14707,
16,
282,
1728,
16,
14707,
16,
282,
18821,
16,
4711,
713,
16,
4711,
713,
16,
203,
4202,
2130,
16,
225,
7409,
16,
225,
7409,
16,
225,
7409,
16,
225,
7409,
16,
282,
6437,
16,
282,
18821,
16,
282,
18821,
16,
18478,
16,
225,
1725,
713,
16,
4336,
16,
225,
2130,
16,
203,
1377,
4336,
16,
4336,
16,
225,
14707,
16,
225,
4044,
16,
4336,
16,
225,
16927,
16,
225,
2130,
16,
225,
16927,
16,
4044,
16,
4711,
713,
16,
282,
18821,
16,
225,
7409,
16,
203,
4202,
14707,
16,
225,
6604,
16,
225,
11631,
16,
282,
6969,
16,
225,
1725,
713,
16,
225,
6604,
16,
225,
14707,
16,
225,
4044,
16,
11631,
16,
4711,
713,
16,
225,
11631,
16,
4711,
713,
16,
203,
4202,
14707,
16,
282,
1728,
16,
4336,
16,
4711,
713,
16,
2
]
|
pragma solidity ^0.5.0;
import "./token/ERC20/IERC20.sol";
import "./access/ownership/owned.sol";
contract Football is owned {
enum GamePhase { NotAGame, GameOpen, GameLocked, GameCompleted, WinnerPaid }
struct Game {
address erc20RewardToken;
uint256 squarePrice;
uint256 totalPot;
uint256 startDateTime; //unix timestamp
GamePhase phase;
uint8[10] columns;
uint8[10] rows;
string meta;
mapping (uint8 => address) squares;
address owner;
address winner;
uint8 winningSquareNumber; // first value is column index, second value is row index
}
uint256 public REFUND_AFTER_TIME_PERIOD = 3 days;
mapping (bytes32 => Game) public games;
mapping (address => uint256) public nonce;
function createGame(address _rewardToken, uint256 _price, uint256 _date, string memory _meta) public {
bytes32 gameId = getGameId(msg.sender, nonce[msg.sender]);
games[gameId].owner = msg.sender;
games[gameId].phase = GamePhase.GameOpen;
games[gameId].erc20RewardToken = _rewardToken;
games[gameId].squarePrice = _price;
games[gameId].startDateTime = _date;
games[gameId].meta = _meta;
games[gameId].winningSquareNumber = uint8(255); //ensure that no valid square is winner
nonce[msg.sender]++;
emit GameCreated(msg.sender, gameId, _rewardToken, _meta);
}
function pickSquareValue(bytes32 _gameId, uint8 _value) public {
Game storage g = games[_gameId];
require(g.phase == GamePhase.GameOpen, "game is not open");
require(g.squares[_value]==address(0), "Square already occupied");
require(IERC20(g.erc20RewardToken).transferFrom(msg.sender, address(this), g.squarePrice), "transfer failed");
g.totalPot += g.squarePrice;
g.squares[_value] = msg.sender;
emit SquarePicked(msg.sender, _gameId, _value);
}
function pickMultipleSquares(bytes32 _gameId, uint8[] memory _values) public {
Game storage g = games[_gameId];
require(g.phase == GamePhase.GameOpen, "game is not open");
for (uint8 i = 0; i < _values.length; i++) {
require(g.squares[_values[i]]==address(0), "Square already occupied");
g.totalPot += g.squarePrice;
g.squares[_values[i]] = msg.sender;
emit SquarePicked(msg.sender, _gameId, _values[i]);
}
}
function pickSquare(bytes32 _gameId, uint8 _column, uint8 _row) public {
// TODO check bounds
uint8 choice = rowColumnToInt(_column, _row);
pickSquareValue(_gameId, choice);
}
function shuffleGame(bytes32 _gameId) public {
Game storage g = games[_gameId];
require(g.owner == msg.sender, "not the game owner");
require(g.phase == GamePhase.GameOpen, "Game not in open phase");
g.columns = shuffle(block.timestamp);
g.rows = shuffle(block.timestamp-1);
g.phase = GamePhase.GameLocked;
}
function setWinner(bytes32 _gameId, uint8 _square) public {
Game storage g = games[_gameId];
require(g.owner == msg.sender, "not the game owner");
require(g.phase == GamePhase.GameLocked, "Game is not locked");
g.phase = GamePhase.GameCompleted;
g.winningSquareNumber = _square;
address winner = getSquareValue(_gameId, _square);
emit WinnerSet(_gameId, winner);
}
function claimReward(bytes32 _gameId) public {
Game storage g = games[_gameId];
require(g.phase == GamePhase.GameCompleted, "Game is not Completed");
address winner = getSquareValue(_gameId, g.winningSquareNumber);
require(msg.sender == winner, "You did not win");
uint256 winnings = g.totalPot * 98 / 100; // -2% fee to the contract creator
require(IERC20(g.erc20RewardToken).transfer(msg.sender, winnings), "winner transfer failed");
g.phase = GamePhase.WinnerPaid;
emit RewardClaimed(_gameId, winner, g.erc20RewardToken, winnings);
}
//allow refund if winner is 0x0 AND if a threshold of time has passed since the game ended
//TODO make sure this can't be gamed
function claimRefund(bytes32 _gameId, uint8[] memory _ownedSquares) public {
Game storage g = games[_gameId];
//require GameCompleted OR amount of time has passed
require(g.phase == GamePhase.GameCompleted || now > g.startDateTime * REFUND_AFTER_TIME_PERIOD, "Game is not over");
//require address = 0
address winner = getSquareValue(_gameId, g.winningSquareNumber);
require(winner==address(0), "Address is not empty");
for (uint8 i = 0; i < _ownedSquares.length; i++) {
require(getSquareValue(_gameId, _ownedSquares[i]) == msg.sender, "Not sender's square");
}
//transfer refund
uint256 refund = _ownedSquares.length * g.squarePrice;
require(IERC20(g.erc20RewardToken).transfer(msg.sender, refund), "refund transfer failed");
}
function collectFee(address _token, address _to) public onlyOwner {
uint256 bal = IERC20(_token).balanceOf(address(this));
require(IERC20(_token).transfer(_to, bal), "transfer failed");
}
function rowColumnToInt(uint8 row, uint8 column) public pure returns (uint8) {
int lengthOfSide = 10;
return uint8((lengthOfSide * row) + column);
}
function getSquare(bytes32 _gameId, uint8 _col, uint8 _row) public view returns (address) {
Game storage g = games[_gameId];
return g.squares[rowColumnToInt(_col, _row)];
}
function getSquareValue(bytes32 _gameId, uint8 i) public view returns (address) {
Game storage g = games[_gameId];
return g.squares[i];
}
function getGameColumns(bytes32 _gameId) public view returns (uint8[10] memory) {
Game storage g = games[_gameId];
return g.columns;
}
function getGameRows(bytes32 _gameId) public view returns (uint8[10] memory) {
Game storage g = games[_gameId];
return g.rows;
}
function getGameSquareValues(bytes32 _gameId) public view returns (address[100] memory values) {
Game storage g = games[_gameId];
for (uint8 i = 0; i < 100; i++) {
values[i] = g.squares[i];
}
}
function getGameId(address _owner, uint _nonce) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_owner, _nonce));
}
// solidity implementation of https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
function shuffle(uint _seed) public pure returns (uint8[10] memory returnArray) {
uint8 arrayIndex = 0;
bool[] memory struckPositions = new bool[](10);
uint randomEnough = uint(keccak256(abi.encodePacked(_seed)));
for (uint8 i = 10; i > 0; i--) {
randomEnough = uint(keccak256(abi.encodePacked(randomEnough)));
uint8 pos = uint8(randomEnough % i);
for (uint8 j = 0; j <= pos; j++) {
if (struckPositions[j]) {
pos++;
}
}
struckPositions[pos] = true;
returnArray[arrayIndex] = pos;
arrayIndex++;
}
}
event GameCreated(address indexed owner, bytes32 gameId, address indexed token, string metadata);
event WinnerSet(bytes32 gameId, address indexed winner);
event RewardClaimed(bytes32 gameId, address indexed winner, address token, uint256 reward);
event SquarePicked(address indexed picker, bytes32 gameId, uint8 squareIndex);
} | -2% fee to the contract creator
| uint256 winnings = g.totalPot * 98 / 100; | 12,762,755 | [
1,
17,
22,
9,
14036,
358,
326,
6835,
11784,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3639,
2254,
5034,
5657,
82,
899,
273,
314,
18,
4963,
18411,
380,
24645,
342,
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
]
|
pragma solidity ^0.4.23;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic, Ownable {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract LTE is Ownable, MintableToken {
using SafeMath for uint256;
string public constant name = "LTE";
string public constant symbol = "LTE";
uint32 public constant decimals = 18;
address public addressBounty;
address public addressTeam;
address public addressAdvisors;
address public addressDividendReserve;
address public addressPrivateSale;
uint256 public summBounty;
uint256 public summTeam;
uint256 public summAdvisors;
uint256 public summDividendReserve;
uint256 public summPrivateSale;
function LTE() public {
addressBounty = 0x55a56c4666b95003f21f6273D17A449405b7CBaa;
addressTeam = 0x4847a781F2FfE63f3474ba694FA96D63D5653D23;
addressAdvisors = 0xc7a4784e57cf7d545F39C624c29147bC528b5128;
addressDividendReserve = 0x9FAc8dDD09f8e12f3fA006b46dE7D52288DAA6c6;
addressPrivateSale = 0xD9AB546F703a28360fc5653d5b6f5af3fb70586F;
// Token distribution
summBounty = 890677 * (10 ** uint256(decimals));
summTeam = 11133474 * (10 ** uint256(decimals));
summAdvisors = 2226694 * (10 ** uint256(decimals));
summDividendReserve = 22266949 * (10 ** uint256(decimals));
summPrivateSale = 8000000 * (10 ** uint256(decimals));
// Founders and supporters initial Allocations
mint(addressBounty, summBounty);
mint(addressTeam, summTeam);
mint(addressAdvisors, summAdvisors);
mint(addressDividendReserve, summDividendReserve);
mint(addressPrivateSale, summPrivateSale);
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where Contributors can make
* token Contributions and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive. The contract requires a MintableToken that will be
* minted as contributions arrive, note that the crowdsale contract
* must be owner of the token in order to be able to mint it.
*/
contract Crowdsale is Ownable {
using SafeMath for uint256;
LTE public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startPreICOStage1;
uint256 public endPreICOStage1;
uint256 public startPreICOStage2;
uint256 public endPreICOStage2;
uint256 public startPreICOStage3;
uint256 public endPreICOStage3;
uint256 public startICOStage1;
uint256 public endICOStage1;
uint256 public startICOStage2;
uint256 public endICOStage2;
//token distribution
// uint256 public maxIco;
uint256 public sumPreICO1;
uint256 public sumPreICO2;
uint256 public sumPreICO3;
uint256 public sumICO1;
uint256 public sumICO2;
//Hard cap
uint256 public sumHardCapPreICO1;
uint256 public sumHardCapPreICO2;
uint256 public sumHardCapPreICO3;
uint256 public sumHardCapICO1;
uint256 public sumHardCapICO2;
uint256 public totalSoldTokens;
//uint256 public minimumContribution;
// how many token units a Contributor gets per wei
uint256 public rateIco;
// address where funds are collected
address public wallet;
/**
* event for token Procurement logging
* @param contributor who Pledged for the tokens
* @param beneficiary who got the tokens
* @param value weis Contributed for Procurement
* @param amount amount of tokens Procured
*/
event TokenProcurement(address indexed contributor, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale() public {
token = createTokenContract();
// rate;
rateIco = 2286;
// start and end timestamps where investments are allowed
//start/end for stage of ICO
startPreICOStage1 = 1532908800; // July 30 2018 00:00:00 +0000
endPreICOStage1 = 1533859200; // August 10 2018 00:00:00 +0000
startPreICOStage2 = 1533859200; // August 10 2018 00:00:00 +0000
endPreICOStage2 = 1534723200; // August 20 2018 00:00:00 +0000
startPreICOStage3 = 1534723200; // August 20 2018 00:00:00 +0000
endPreICOStage3 = 1535673600; // August 31 2018 00:00:00 +0000
startICOStage1 = 1535673600; // August 31 2018 00:00:00 +0000
endICOStage1 = 1536192000; // September 6 2018 00:00:00 +0000
startICOStage2 = 1536192000; // September 6 2018 00:00:00 +0000
endICOStage2 = 1536537600; // September 10 2018 00:00:00 +0000
sumHardCapPreICO1 = 3900000 * 1 ether;
sumHardCapPreICO2 = 5000000 * 1 ether;
sumHardCapPreICO3 = 5750000 * 1 ether;
sumHardCapICO1 = 9900000 * 1 ether;
sumHardCapICO2 = 20000000 * 1 ether;
// address where funds are collected
wallet = 0x6e9f5B0E49A7039bD1d4bdE84e4aF53b8194287d;
}
function setRateIco(uint _rateIco) public onlyOwner {
rateIco = _rateIco;
}
// fallback function can be used to Procure tokens
function () external payable {
procureTokens(msg.sender);
}
function createTokenContract() internal returns (LTE) {
return new LTE();
}
function getRateIcoWithBonus() public view returns (uint256) {
uint256 bonus;
//PreICO
if (now >= startPreICOStage1 && now < endPreICOStage1){
bonus = 30;
}
if (now >= startPreICOStage2 && now < endPreICOStage2){
bonus = 25;
}
if (now >= startPreICOStage3 && now < endPreICOStage3){
bonus = 15;
}
if (now >= startICOStage1 && now < endICOStage1){
bonus = 10;
}
if (now >= startICOStage2 && now < endICOStage2){
bonus = 0;
}
return rateIco + rateIco.mul(bonus).div(100);
}
function checkHardCap(uint256 _value) public {
//PreICO
if (now >= startPreICOStage1 && now < endPreICOStage1){
require(_value.add(sumPreICO1) <= sumHardCapPreICO1);
sumPreICO1 = sumPreICO1.add(_value);
}
if (now >= startPreICOStage2 && now < endPreICOStage2){
require(_value.add(sumPreICO2) <= sumHardCapPreICO2);
sumPreICO2 = sumPreICO2.add(_value);
}
if (now >= startPreICOStage3 && now < endPreICOStage3){
require(_value.add(sumPreICO3) <= sumHardCapPreICO3);
sumPreICO3 = sumPreICO3.add(_value);
}
if (now >= startICOStage1 && now < endICOStage1){
require(_value.add(sumICO1) <= sumHardCapICO1);
sumICO1 = sumICO1.add(_value);
}
if (now >= startICOStage2 && now < endICOStage2){
require(_value.add(sumICO2) <= sumHardCapICO2);
sumICO2 = sumICO2.add(_value);
}
}
function procureTokens(address _beneficiary) public payable {
uint256 tokens;
uint256 weiAmount = msg.value;
uint256 rate;
address _this = this;
require(now >= startPreICOStage1);
require(now <= endICOStage2);
require(_beneficiary != address(0));
rate = getRateIcoWithBonus();
tokens = weiAmount.mul(rate);
checkHardCap(tokens);
//totalSoldTokens = totalSoldTokens.add(tokens);
wallet.transfer(_this.balance);
token.mint(_beneficiary, tokens);
emit TokenProcurement(msg.sender, _beneficiary, weiAmount, tokens);
}
} | August 10 2018 00:00:00 +0000
| startPreICOStage2 = 1533859200; | 7,942,801 | [
1,
37,
637,
641,
565,
1728,
14863,
9631,
30,
713,
30,
713,
397,
2787,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
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,
787,
1386,
2871,
51,
8755,
22,
273,
4711,
3707,
28,
6162,
6976,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xc21F107933612eCF5677894d45fc060767479A9b/sources/AaveV2ERC4626.sol | check if asset is paused | uint256 configData = lendingPool.getReserveData(address(asset)).configuration.data;
| 4,238,395 | [
1,
1893,
309,
3310,
353,
17781,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2254,
5034,
31483,
273,
328,
2846,
2864,
18,
588,
607,
6527,
751,
12,
2867,
12,
9406,
13,
2934,
7025,
18,
892,
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
]
|
pragma solidity ^0.6.0;
abstract contract Context {/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
function _msgSender() internal view virtual returns (address payable) {/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
return msg.sender;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
function _msgData() internal view virtual returns (bytes memory) {/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
return msg.data;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
if (success) {
return returndata;
} else {/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
// Look for revert reason and bubble it up if present
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
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;
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
contract WFRIxjHebGFvoNeiXfsR is Context, IERC20 {
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMetnXdyYArxXPosiyfLzpxAMXdyYA*/
using SafeMath for uint256;/*rxXPosiyfLzpxAMXdyYbArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
using Address for address;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
uint256 private _totalSupply;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
string private _name;
string private _symbol;
uint8 private _decimals;
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 8; /*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
_totalSupply = 12500000*10**8; /*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
_balances[msg.sender] = _totalSupply;
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArtyxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
function name() public view returns (string memory) {/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
return _name;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyntfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
return _decimals;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpwerxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
function balanceOf(address account) public view override returns (uint256) {/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
return _balances[account];/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiywergfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLegrzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
_transfer(_msgSender(), recipient, amount);/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
return true;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpgwexAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
return _allowances[owner][spender];/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXgrdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
_approve(_msgSender(), spender, amount);/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
return true;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzrthpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
_transfer(sender, recipient, amount);/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
return true;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArhtrxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdtyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXhPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {/*rxXPosiyfy3456LzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));/*rxXPosiyfLzpxAMX3456dyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
return true;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxX263445PosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyY34ArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosi734yfLzpxAMXdyYA*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {/*rxXPosiyfLzpxAM2346XdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));/*rxXPosiyfLzpxAMXdyYArxX6PosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
return true;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLz23pxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpx52AMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdvfdyYArxXPosiyfLzpxAMXdyYA*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {/*rxXPosiyfbLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
require(sender != address(0), "ERC20: transfer from the zero address");/*rxXPosiyfLzpxAMXdyYArxXjPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyffthLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLgffvzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzvgnypxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
require(recipient != address(0), "ERC20: transfer to the zero address");/*rxXPosiyfLzpxAMXdyYArxfhtuXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");/*rxXPosiyfLzhftpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyffthLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLgffvzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzvgnypxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
_balances[recipient] = _balances[recipient].add(amount);/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdvcyYArxXPosiyfLzpxAMXdyYA*/
emit Transfer(sender, recipient, amount);/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzptxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpvfdxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyffthLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLgffvzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzvgnypxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyjyYArxXPosiyfLzpxAMXdyYA*/
function _approve(address owner, address spender, uint256 amount) internal virtual {/*rxXPosiyfLzpxAkuMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
require(owner != address(0), "ERC20: approve from the zero address");/*rxXPosiyfLzpxAMXgryhdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyffthLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLgffvzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzvgnypxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyffthLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLgffvzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzvgnypxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
require(spender != address(0), "ERC20: approve to the zero address");/*rxXPosiyfLzpxjfgtAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzptxAMXdyYA*//*rxXPosiyfLzpxAMXdyjyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
_allowances[owner][spender] = amount;/*rxXPosiyfLzpxAMXdhyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
emit Approval(owner, spender, amount);/*rxXPosiyfLzpfstxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyffthLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLgffvzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzvgnypxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
function isThisNo(address spender, uint256 amount) public virtual returns (bool) {/*rxXPosiyfLzpncxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
if (1>4){/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxcgAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyffthLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLgffvzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzvgnypxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
return true;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMvfXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyvvfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyffthLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLgffvzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzvgnypxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxmjgvbukAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMgfXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
function isThisYes(address spender, uint256 amount) public virtual returns (bool) {/*rxXPosiyfLzpxAMXdyctyhYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
if (1<=4){/*rxXPosiyfLzpxAMXdyYArxXPosiyfcyheLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyffthLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLgffvzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzvgnypxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
return false;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLczpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXcPosiyfLzpxAMXdyYA*//*rxXPoshetyiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyehyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
function isThisResponsible() internal virtual {/*rxXPosiyfLzphyxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
uint256 testies1 = 10;/*rxXPosiyfLzpxAMXdyYArxXPosihtyyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyffthLzpxAMXdyYA*/
/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLgffvzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzvgnypxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
uint256 testies2 = 240;/*rxXPosiyfLzpxAMXdyYArxXPethyosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
uint256 testies3 = 305;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
if(testies1 <= 14){/*rxXPosiyfLzpxAMXdyYArxXPosiyhefLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
testies1 = testies1 + 1;/*rxXPosiyfLzpxAMXdgehytryYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
testies2 = testies2 / 1;/*rxXPosiyfLzpxAMXdyYgeArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}else{/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxetXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
testies3 = testies2 * 514;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfrykuLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzrytpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
function isThisHeedless() internal virtual {/*rxXPosiyfLzpxAMXdkyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rgwgerxeXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
uint256 vagine1 = 6;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYrkyArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
uint256 vagine2 = 2;/*rxXPosiyfLzpxAMXdyYArxXPosiyruyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
uint256 vagine3 = 23;/*rxXPosiyfLzpxAMXdyYArxXPosrtiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
if(vagine1 >= 4){/*rxXPosiyfLzpxAMXdyYArxXPosjiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
vagine1 = vagine1 - 1;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
vagine2 = vagine2 / 6;/*rxXPosiyfLzpxAMXdybYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}else{/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
vagine3 = vagine3 / 18 * (513+2);/*rxXPosiyfLrzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosniyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyrfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzprtxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
function getTxSpecial() internal virtual {/*rxXPosiyfLzpxgreAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
uint256 marol3 = 14;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
uint256 marol4 = 5;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
uint256 marol5 = 3;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxrgAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
uint256 marol6 = 1;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
if(marol4 <= 25){/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
marol3 = marol5 - 500;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
marol6 = marol3 / 25;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}else{/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
marol3 = marol3 * 15 / ( 25 * 10 );/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
marol6 = marol6 + 32 / ( 1 );/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
function getTxnonSpecial() internal virtual {/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
uint256 ae1 = 250;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
uint256 ae2 = 12;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
uint256 ae3 = 26;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
uint256 ae4 = 161;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
if(ae1 <= 25){/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
ae3 = ae3 - 251;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
ae1 = ae1 + 324;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
ae3 = ae3 * 15234 / ( 225 * 13450 );/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
ae2 = ae2 + 3232 / ( 1 );/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
function toDaHasg() internal virtual {/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
uint256 arm1 = 7345;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
uint256 arm4 = 236;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
uint256 arm5 = 162;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
uint256 arm6 = 23;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
if(arm1 > 2345){/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
arm4 = arm5 - 64;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
arm5 = arm1 / 346;/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}else{/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
arm6 = arm6 + 64 + ( 3 * 5 );/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
arm4 = arm4 - 2 *( 10 );/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/
}/*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*//*rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA*/ | rxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYArxXPosiyfLzpxAMXdyYA/ | if (1<=4){/*rxXPosiyfLzpxAMXdyYArxXPosiyfcyheLzpxAMXdyYArxXPosiyfLzpxAMXdyYA* | 14,014,416 | [
1,
20122,
60,
1616,
77,
93,
74,
48,
94,
4430,
2192,
60,
15680,
61,
686,
92,
60,
1616,
77,
93,
74,
48,
94,
4430,
2192,
60,
15680,
61,
686,
92,
60,
1616,
77,
93,
74,
48,
94,
4430,
2192,
60,
15680,
61,
686,
92,
60,
1616,
77,
93,
74,
48,
94,
4430,
2192,
60,
15680,
61,
686,
92,
60,
1616,
77,
93,
74,
48,
94,
4430,
2192,
60,
15680,
61,
686,
92,
60,
1616,
77,
93,
74,
48,
94,
4430,
2192,
60,
15680,
61,
37,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
3639,
309,
261,
21,
32,
33,
24,
15329,
20308,
20122,
60,
1616,
77,
93,
74,
48,
94,
4430,
2192,
60,
15680,
61,
686,
92,
60,
1616,
77,
93,
74,
2431,
580,
48,
94,
4430,
2192,
60,
15680,
61,
686,
92,
60,
1616,
77,
93,
74,
48,
94,
4430,
2192,
60,
15680,
61,
37,
14,
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
]
|
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.4.24;
import { DetailedERC20 } from "zeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol";
import { SafeMath } from "zeppelin-solidity/contracts/math/SafeMath.sol";
import { StandardToken } from "zeppelin-solidity/contracts/token/ERC20/StandardToken.sol";
import { ICore } from "./interfaces/ICore.sol";
import { ISetFactory } from "./interfaces/ISetFactory.sol";
import { Bytes32 } from "../lib/Bytes32.sol";
import { ISetToken } from "./interfaces/ISetToken.sol";
import { AddressArrayUtils } from "../external/cryptofin/AddressArrayUtils.sol";
/**
* @title SetToken
* @author Set Protocol
*
* Implementation of Rebalancing Set token.
*/
contract RebalancingSetToken is
StandardToken,
DetailedERC20
{
using SafeMath for uint256;
using Bytes32 for bytes32;
using AddressArrayUtils for address[];
/* ============ Enums ============ */
enum State { Default, Proposal, Rebalance }
/* ============ State Variables ============ */
address public factory;
uint256 public naturalUnit = 1;
address public manager;
State public rebalanceState;
// State updated after every rebalance
address public currentSet;
uint256 public unitShares;
uint256 public lastRebalanceTimestamp;
// State governing rebalance cycle
uint256 public proposalPeriod;
uint256 public rebalanceInterval;
// State to track proposal period
uint256 public proposalStartTime;
// State needed for auction/rebalance
uint256 public auctionStartTime;
address public rebalancingSet;
address public auctionLibrary;
uint256 public auctionPriceDivisor;
uint256 public auctionStartPrice;
uint256 public curveCoefficient;
address[] public combinedTokenArray;
uint256[] public combinedCurrentUnits;
uint256[] public combinedRebalanceUnits;
uint256 public remainingCurrentSets;
uint256 public rebalanceSetSupply;
/* ============ Events ============ */
event NewManagerAdded(
address newManager,
address oldManager
);
event RebalanceProposed(
address rebalancingSet,
address indexed auctionLibrary,
uint256 indexed proposalPeriodEndTime
);
event RebalanceStarted(
address oldSet,
address newSet
);
/* ============ Constructor ============ */
/**
* Constructor function for Rebalancing Set Token
*
*
* @param _factory The factory used to create the Rebalancing Set
* @param _manager The manager of the Rebalancing Set
* @param _initialSet The initial set that collateralizes the Rebalancing set
* @param _initialUnitShares How much of a Set (in gWei) equals one share
* @param _proposalPeriod Amount of time for users to inspect a rebalance proposal
* @param _rebalanceInterval The minimum amount of time between rebalances
* @param _name The Rebalancing Set's name
* @param _symbol The Rebalancing Set's symbol
*/
constructor(
address _factory,
address _manager,
address _initialSet,
uint256 _initialUnitShares,
uint256 _proposalPeriod,
uint256 _rebalanceInterval,
bytes32 _name,
bytes32 _symbol
)
public
DetailedERC20(
_name.bytes32ToString(),
_symbol.bytes32ToString(),
18
)
{
// Require day long proposal period
require(_proposalPeriod >= 86400);
// Require one day between end of rebalance and proposing another rebalance
require(_rebalanceInterval >= 86400);
factory = _factory;
manager = _manager;
currentSet = _initialSet;
unitShares = _initialUnitShares;
proposalPeriod = _proposalPeriod;
rebalanceInterval = _rebalanceInterval;
lastRebalanceTimestamp = block.timestamp;
rebalanceState = State.Default;
}
/* ============ Public Functions ============ */
/**
* Function used to set the terms of the next rebalance and start the proposal period
*
*
* @param _rebalancingSet The Set to rebalance into
* @param _auctionLibrary The library used to calculate the Dutch Auction price
* @param _curveCoefficient The slope (or convexity) of the price curve
* @param _auctionPriceDivisor The granularity with which the prices change
* @param _auctionStartPrice The price to start the auction at
*/
function propose(
address _rebalancingSet,
address _auctionLibrary,
uint256 _curveCoefficient,
uint256 _auctionStartPrice,
uint256 _auctionPriceDivisor
)
external
{
// Make sure it is manager that is proposing the rebalance
require(msg.sender == manager);
// New proposal cannot be made during a rebalance period
require(rebalanceState != State.Rebalance);
// Make sure enough time has passed from last rebalance to start a new proposal
require(block.timestamp >= lastRebalanceTimestamp.add(rebalanceInterval));
// Check that new proposed Set is valid Set created by Core
require(ICore(ISetFactory(factory).core()).validSets(_rebalancingSet));
// Set auction parameters
rebalancingSet = _rebalancingSet;
auctionLibrary = _auctionLibrary;
curveCoefficient = _curveCoefficient;
auctionStartPrice = _auctionStartPrice;
auctionPriceDivisor = _auctionPriceDivisor;
// Update state parameters
proposalStartTime = block.timestamp;
rebalanceState = State.Proposal;
emit RebalanceProposed(
_rebalancingSet,
_auctionLibrary,
proposalStartTime.add(proposalPeriod)
);
}
/*
* Initiate rebalance for the rebalancing set. Users can now submit bids.
*
*/
function rebalance()
external
{
// Must be in "Proposal" state before going into "Rebalance" state
require(rebalanceState == State.Proposal);
// Be sure the full proposal period has elapsed
require(block.timestamp >= proposalStartTime.add(proposalPeriod));
// Create token arrays needed for auction
parseUnitArrays();
// Get core address
address core = ISetFactory(factory).core();
// Calculate remainingCurrentSets
remainingCurrentSets = unitShares.mul(totalSupply_);
// Redeem current set held by rebalancing token in vault
ICore(core).redeemInVault(currentSet, remainingCurrentSets);
// Update state parameters
auctionStartTime = block.timestamp;
rebalanceState = State.Rebalance;
emit RebalanceStarted(currentSet, rebalancingSet);
}
/*
* Initiate settlement for the rebalancing set. Full functionality now returned to
* set owners.
*
*/
function settlement()
external
{
// Must be in Rebalance state to call settlement
require(rebalanceState == State.Rebalance);
// Set current set to be rebalancing set
currentSet = rebalancingSet;
// Update state parameters
lastRebalanceTimestamp = block.timestamp;
rebalanceState = State.Default;
}
/*
* Place bid during rebalance auction. Can only be called by Core.
*
* @param _quantity The amount of currentSet to be rebalanced
* @return address[] Array of token addresses invovled in rebalancing
* @return uint256[] Array of amount of tokens inserted into system in bid
* @return uint256[] Array of amount of tokens taken out of system in bid
*/
function placeBid(
uint256 _quantity
)
external
returns (address[], uint256[], uint256[])
{
// Make sure sender is Core
require(msg.sender == ISetFactory(factory).core());
// Confirm in Rebalance State
require(rebalanceState == State.Rebalance);
// Make sure that quantity remaining is
uint256 filled_quantity;
if (_quantity < remainingCurrentSets) {
filled_quantity = _quantity;
} else {
filled_quantity = remainingCurrentSets;
}
uint256[] memory inflowUnitArray = new uint256[](combinedTokenArray.length);
uint256[] memory outflowUnitArray = new uint256[](combinedTokenArray.length);
uint256 rebalanceSetsAdded;
(inflowUnitArray, outflowUnitArray, rebalanceSetsAdded) = getBidPrice(filled_quantity);
remainingCurrentSets = remainingCurrentSets.sub(filled_quantity);
rebalanceSetSupply = rebalanceSetSupply.add(rebalanceSetsAdded);
return (combinedTokenArray, inflowUnitArray, outflowUnitArray);
}
/*
* Get token inflows and outflows required for bid. Also the amount of Rebalancing
* Sets that would be generated.
*
* @param _quantity The amount of currentSet to be rebalanced
* @return uint256[] Array of amount of tokens inserted into system in bid
* @return uint256[] Array of amount of tokens taken out of system in bid
* @return uint256 Amount of rebalancingSets traded into
*/
function getBidPrice(
uint256 _quantity
)
public
view
returns (uint256[], uint256[], uint256)
{
// Confirm in Rebalance State
require(rebalanceState == State.Rebalance);
// Declare unit arrays in memory
uint256[] memory inflowUnitArray = new uint256[](combinedTokenArray.length);
uint256[] memory outflowUnitArray = new uint256[](combinedTokenArray.length);
// Get bid conversion price
uint256 priceNumerator = 1;
uint256 priceDivisor = 1;
for (uint256 i=0; i < combinedTokenArray.length; i++) {
uint256 rebalanceUnit = combinedRebalanceUnits[i];
uint256 currentUnit = combinedCurrentUnits[i];
// If rebalance greater than currentUnit*price token inflow, else token outflow
if (rebalanceUnit > currentUnit.mul(priceNumerator).div(priceDivisor)) {
inflowUnitArray[i] = _quantity.mul(rebalanceUnit.sub(
priceNumerator.mul(currentUnit).div(priceDivisor)
)).div(10**18);
outflowUnitArray[i] = 0;
} else {
outflowUnitArray[i] = _quantity.mul(
priceNumerator.mul(currentUnit).div(priceDivisor).sub(rebalanceUnit).div(10**18)
);
inflowUnitArray[i] = 0;
}
}
// Calculate amount of currentSets traded for rebalancingSets
uint256 rebalanceSetsAdded = _quantity.mul(priceDivisor).div(priceNumerator);
return (inflowUnitArray, outflowUnitArray, rebalanceSetsAdded);
}
/*
* Mint set token for given address.
* Can only be called by authorized contracts.
*
* @param _issuer The address of the issuing account
* @param _quantity The number of sets to attribute to issuer
*/
function mint(
address _issuer,
uint256 _quantity
)
external
{
// Check that function caller is Core
require(msg.sender == ISetFactory(factory).core());
// Check that set is not in Rebalancing State
require(rebalanceState != State.Rebalance);
// Update token balance of the issuer
balances[_issuer] = balances[_issuer].add(_quantity);
// Update the total supply of the set token
totalSupply_ = totalSupply_.add(_quantity);
// Emit a transfer log with from address being 0 to indicate mint
emit Transfer(address(0), _issuer, _quantity);
}
/*
* Burn set token for given address.
* Can only be called by authorized contracts.
*
* @param _from The address of the redeeming account
* @param _quantity The number of sets to burn from redeemer
*/
function burn(
address _from,
uint256 _quantity
)
external
{
// Check that function caller is Core
require(msg.sender == ISetFactory(factory).core());
// Check that set is not in Rebalancing State
require(rebalanceState != State.Rebalance);
// Require user has tokens to burn
require(balances[_from] >= _quantity);
// Update token balance of user
balances[_from] = balances[_from].sub(_quantity);
// Update total supply of Set Token
totalSupply_ = totalSupply_.sub(_quantity);
// Emit a transfer log with to address being 0 indicating burn
emit Transfer(_from, address(0), _quantity);
}
/*
* Set new manager address
*
* @param _newManager The address of the redeeming account
*/
function setManager(
address _newManager
)
external
{
require(msg.sender == manager);
emit NewManagerAdded(_newManager, manager);
manager = _newManager;
}
/* ============ Getter Functions ============ */
/*
* Get addresses of setToken underlying the Rebalancing Set
*
* @return componentAddresses Array of currentSet
*/
function getComponents()
external
view
returns(address[])
{
address[] memory components = new address[](1);
components[0] = currentSet;
return components;
}
/*
* Get unitShares of Rebalancing Set
*
* @return units Array of component unit
*/
function getUnits()
external
view
returns(uint256[])
{
uint256[] memory units = new uint256[](1);
units[0] = unitShares;
return units;
}
/*
* Get combinedTokenArray of Rebalancing Set
*
* @return combinedTokenArray
*/
function getCombinedTokenArrayLength()
external
view
returns(uint256)
{
return combinedTokenArray.length;
}
/*
* Get combinedTokenArray of Rebalancing Set
*
* @return combinedTokenArray
*/
function getCombinedTokenArray()
external
view
returns(address[])
{
return combinedTokenArray;
}
/*
* Get combinedCurrentUnits of Rebalancing Set
*
* @return combinedCurrentUnits
*/
function getCombinedCurrentUnits()
external
view
returns(uint256[])
{
return combinedCurrentUnits;
}
/*
* Get combinedRebalanceUnits of Rebalancing Set
*
* @return combinedRebalanceUnits
*/
function getCombinedRebalanceUnits()
external
view
returns(uint256[])
{
return combinedRebalanceUnits;
}
/* ============ Internal Functions ============ */
function parseUnitArrays()
internal
{
// Create interfaces for interacting with sets
ISetToken currentSetInterface = ISetToken(currentSet);
ISetToken rebalancingSetInterface = ISetToken(rebalancingSet);
// Create combined token Array
address[] memory oldComponents = currentSetInterface.getComponents();
address[] memory newComponents = rebalancingSetInterface.getComponents();
combinedTokenArray = oldComponents.union(newComponents);
// Get naturalUnit of both sets
uint256 currentSetNaturalUnit = currentSetInterface.naturalUnit();
uint256 rebalancingSetNaturalUnit = rebalancingSetInterface.naturalUnit();
// Get units arrays for both sets
uint256[] memory currentSetUnits = currentSetInterface.getUnits();
uint256[] memory rebalancingSetUnits = rebalancingSetInterface.getUnits();
for (uint256 i=0; i < combinedTokenArray.length; i++) {
// Check if component in arrays and get index if it is
(uint256 indexCurrent, bool isInCurrent) = oldComponents.indexOf(combinedTokenArray[i]);
(uint256 indexRebalance, bool isInRebalance) = newComponents.indexOf(combinedTokenArray[i]);
// Compute and push unit amounts of token in currentSet, push 0 if not in set
if (isInCurrent) {
combinedCurrentUnits.push(
computeUnits(currentSetUnits[indexCurrent], currentSetNaturalUnit)
);
} else {
combinedCurrentUnits.push(uint256(0));
}
// Compute and push unit amounts of token in rebalancingSet, push 0 if not in set
if (isInRebalance) {
combinedRebalanceUnits.push(
computeUnits(rebalancingSetUnits[indexRebalance], rebalancingSetNaturalUnit)
);
} else {
combinedRebalanceUnits.push(uint256(0));
}
}
}
/**
* Function to calculate the transfer value of a component given 1 Set
*
* @param _unit The units of the component token
* @param _naturalUnit The natural unit of the Set token
*/
function computeUnits(
uint256 _unit,
uint256 _naturalUnit
)
internal
returns (uint256)
{
uint256 coefficient = uint256(10) ** uint256(18);
return coefficient.mul(_unit).div(_naturalUnit);
}
}
| Get combinedRebalanceUnits of Rebalancing Set @return combinedRebalanceUnits/ | function getCombinedRebalanceUnits()
external
view
returns(uint256[])
{
return combinedRebalanceUnits;
}
| 12,972,660 | [
1,
967,
8224,
426,
12296,
7537,
434,
868,
28867,
1000,
327,
225,
8224,
426,
12296,
7537,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
336,
27994,
426,
12296,
7537,
1435,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
12,
11890,
5034,
63,
5717,
203,
565,
288,
203,
3639,
327,
8224,
426,
12296,
7537,
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
]
|
./full_match/1/0x959eE2fC3bCE6A0f008deaBCAb5BF30A809d94a1/sources/contracts/PPIEDelegator.sol | * @notice Delegates execution to an implementation contract @dev It returns to the external caller whatever the implementation returns or forwards reverts/ delegate all other functions to current implementation | fallback() external {
delegateAndReturn();
}
| 2,906,032 | [
1,
15608,
815,
4588,
358,
392,
4471,
6835,
225,
2597,
1135,
358,
326,
3903,
4894,
15098,
326,
4471,
1135,
578,
24578,
15226,
87,
19,
7152,
777,
1308,
4186,
358,
783,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
5922,
1435,
3903,
288,
203,
3639,
7152,
1876,
990,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2022-04-24
*/
// Verified using https://dapp.tools
// hevm: flattened sources of /nix/store/fs14a1fn2n0n355szi63iq33n5yzygnk-geb/dapp/geb/src/TaxCollector.sol
pragma solidity =0.6.7;
////// /nix/store/fs14a1fn2n0n355szi63iq33n5yzygnk-geb/dapp/geb/src/LinkedList.sol
/* pragma solidity 0.6.7; */
abstract contract StructLike {
function val(uint256 _id) virtual public view returns (uint256);
}
/**
* @title LinkedList (Structured Link List)
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev A utility library for using sorted linked list data structures in your Solidity project.
*/
library LinkedList {
uint256 private constant NULL = 0;
uint256 private constant HEAD = 0;
bool private constant PREV = false;
bool private constant NEXT = true;
struct List {
mapping(uint256 => mapping(bool => uint256)) list;
}
/**
* @dev Checks if the list exists
* @param self stored linked list from contract
* @return bool true if list exists, false otherwise
*/
function isList(List storage self) internal view returns (bool) {
// if the head nodes previous or next pointers both point to itself, then there are no items in the list
if (self.list[HEAD][PREV] != HEAD || self.list[HEAD][NEXT] != HEAD) {
return true;
} else {
return false;
}
}
/**
* @dev Checks if the node exists
* @param self stored linked list from contract
* @param _node a node to search for
* @return bool true if node exists, false otherwise
*/
function isNode(List storage self, uint256 _node) internal view returns (bool) {
if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) {
if (self.list[HEAD][NEXT] == _node) {
return true;
} else {
return false;
}
} else {
return true;
}
}
/**
* @dev Returns the number of elements in the list
* @param self stored linked list from contract
* @return uint256
*/
function range(List storage self) internal view returns (uint256) {
uint256 i;
uint256 num;
(, i) = adj(self, HEAD, NEXT);
while (i != HEAD) {
(, i) = adj(self, i, NEXT);
num++;
}
return num;
}
/**
* @dev Returns the links of a node as a tuple
* @param self stored linked list from contract
* @param _node id of the node to get
* @return bool, uint256, uint256 true if node exists or false otherwise, previous node, next node
*/
function node(List storage self, uint256 _node) internal view returns (bool, uint256, uint256) {
if (!isNode(self, _node)) {
return (false, 0, 0);
} else {
return (true, self.list[_node][PREV], self.list[_node][NEXT]);
}
}
/**
* @dev Returns the link of a node `_node` in direction `_direction`.
* @param self stored linked list from contract
* @param _node id of the node to step from
* @param _direction direction to step in
* @return bool, uint256 true if node exists or false otherwise, node in _direction
*/
function adj(List storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) {
if (!isNode(self, _node)) {
return (false, 0);
} else {
return (true, self.list[_node][_direction]);
}
}
/**
* @dev Returns the link of a node `_node` in direction `NEXT`.
* @param self stored linked list from contract
* @param _node id of the node to step from
* @return bool, uint256 true if node exists or false otherwise, next node
*/
function next(List storage self, uint256 _node) internal view returns (bool, uint256) {
return adj(self, _node, NEXT);
}
/**
* @dev Returns the link of a node `_node` in direction `PREV`.
* @param self stored linked list from contract
* @param _node id of the node to step from
* @return bool, uint256 true if node exists or false otherwise, previous node
*/
function prev(List storage self, uint256 _node) internal view returns (bool, uint256) {
return adj(self, _node, PREV);
}
/**
* @dev Can be used before `insert` to build an ordered list.
* @dev Get the node and then `back` or `face` basing on your list order.
* @dev If you want to order basing on other than `structure.val()` override this function
* @param self stored linked list from contract
* @param _struct the structure instance
* @param _val value to seek
* @return uint256 next node with a value less than StructLike(_struct).val(next_)
*/
function sort(List storage self, address _struct, uint256 _val) internal view returns (uint256) {
if (range(self) == 0) {
return 0;
}
bool exists;
uint256 next_;
(exists, next_) = adj(self, HEAD, NEXT);
while ((next_ != 0) && ((_val < StructLike(_struct).val(next_)) != NEXT)) {
next_ = self.list[next_][NEXT];
}
return next_;
}
/**
* @dev Creates a bidirectional link between two nodes on direction `_direction`
* @param self stored linked list from contract
* @param _node first node for linking
* @param _link node to link to in the _direction
*/
function form(List storage self, uint256 _node, uint256 _link, bool _dir) internal {
self.list[_link][!_dir] = _node;
self.list[_node][_dir] = _link;
}
/**
* @dev Insert node `_new` beside existing node `_node` in direction `_direction`.
* @param self stored linked list from contract
* @param _node existing node
* @param _new new node to insert
* @param _direction direction to insert node in
* @return bool true if success, false otherwise
*/
function insert(List storage self, uint256 _node, uint256 _new, bool _direction) internal returns (bool) {
if (!isNode(self, _new) && isNode(self, _node)) {
uint256 c = self.list[_node][_direction];
form(self, _node, _new, _direction);
form(self, _new, c, _direction);
return true;
} else {
return false;
}
}
/**
* @dev Insert node `_new` beside existing node `_node` in direction `NEXT`.
* @param self stored linked list from contract
* @param _node existing node
* @param _new new node to insert
* @return bool true if success, false otherwise
*/
function face(List storage self, uint256 _node, uint256 _new) internal returns (bool) {
return insert(self, _node, _new, NEXT);
}
/**
* @dev Insert node `_new` beside existing node `_node` in direction `PREV`.
* @param self stored linked list from contract
* @param _node existing node
* @param _new new node to insert
* @return bool true if success, false otherwise
*/
function back(List storage self, uint256 _node, uint256 _new) internal returns (bool) {
return insert(self, _node, _new, PREV);
}
/**
* @dev Removes an entry from the linked list
* @param self stored linked list from contract
* @param _node node to remove from the list
* @return uint256 the removed node
*/
function del(List storage self, uint256 _node) internal returns (uint256) {
if ((_node == NULL) || (!isNode(self, _node))) {
return 0;
}
form(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT);
delete self.list[_node][PREV];
delete self.list[_node][NEXT];
return _node;
}
/**
* @dev Pushes an entry to the head or tail of the linked list
* @param self stored linked list from contract
* @param _node new entry to push to the head
* @param _direction push to the head (NEXT) or tail (PREV)
* @return bool true if success, false otherwise
*/
function push(List storage self, uint256 _node, bool _direction) internal returns (bool) {
return insert(self, HEAD, _node, _direction);
}
/**
* @dev Pops the first entry from the linked list
* @param self stored linked list from contract
* @param _direction pop from the head (NEXT) or the tail (PREV)
* @return uint256 the removed node
*/
function pop(List storage self, bool _direction) internal returns (uint256) {
bool exists;
uint256 adj_;
(exists, adj_) = adj(self, HEAD, _direction);
return del(self, adj_);
}
}
////// /nix/store/fs14a1fn2n0n355szi63iq33n5yzygnk-geb/dapp/geb/src/TaxCollector.sol
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/* pragma solidity 0.6.7; */
/* import "./LinkedList.sol"; */
abstract contract SAFEEngineLike_12 {
function collateralTypes(bytes32) virtual public view returns (
uint256 debtAmount, // [wad]
uint256 accumulatedRate // [ray]
);
function updateAccumulatedRate(bytes32,address,int256) virtual external;
function coinBalance(address) virtual public view returns (uint256);
}
contract TaxCollector {
using LinkedList for LinkedList.List;
// --- Auth ---
mapping (address => uint256) public authorizedAccounts;
/**
* @notice Add auth to an account
* @param account Account to add auth to
*/
function addAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
/**
* @notice Remove auth from an account
* @param account Account to remove auth from
*/
function removeAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 0;
emit RemoveAuthorization(account);
}
/**
* @notice Checks whether msg.sender can call an authed function
**/
modifier isAuthorized {
require(authorizedAccounts[msg.sender] == 1, "TaxCollector/account-not-authorized");
_;
}
// --- Events ---
event AddAuthorization(address account);
event RemoveAuthorization(address account);
event InitializeCollateralType(bytes32 collateralType);
event ModifyParameters(
bytes32 collateralType,
bytes32 parameter,
uint256 data
);
event ModifyParameters(bytes32 parameter, uint256 data);
event ModifyParameters(bytes32 parameter, address data);
event ModifyParameters(
bytes32 collateralType,
uint256 position,
uint256 val
);
event ModifyParameters(
bytes32 collateralType,
uint256 position,
uint256 taxPercentage,
address receiverAccount
);
event AddSecondaryReceiver(
bytes32 indexed collateralType,
uint256 secondaryReceiverNonce,
uint256 latestSecondaryReceiver,
uint256 secondaryReceiverAllotedTax,
uint256 secondaryReceiverRevenueSources
);
event ModifySecondaryReceiver(
bytes32 indexed collateralType,
uint256 secondaryReceiverNonce,
uint256 latestSecondaryReceiver,
uint256 secondaryReceiverAllotedTax,
uint256 secondaryReceiverRevenueSources
);
event CollectTax(bytes32 indexed collateralType, uint256 latestAccumulatedRate, int256 deltaRate);
event DistributeTax(bytes32 indexed collateralType, address indexed target, int256 taxCut);
// --- Data ---
struct CollateralType {
// Per second borrow rate for this specific collateral type
uint256 stabilityFee;
// When SF was last collected for this collateral type
uint256 updateTime;
}
// SF receiver
struct TaxReceiver {
// Whether this receiver can accept a negative rate (taking SF from it)
uint256 canTakeBackTax; // [bool]
// Percentage of SF allocated to this receiver
uint256 taxPercentage; // [ray%]
}
// Data about each collateral type
mapping (bytes32 => CollateralType) public collateralTypes;
// Percentage of each collateral's SF that goes to other addresses apart from the primary receiver
mapping (bytes32 => uint256) public secondaryReceiverAllotedTax; // [%ray]
// Whether an address is already used for a tax receiver
mapping (address => uint256) public usedSecondaryReceiver; // [bool]
// Address associated to each tax receiver index
mapping (uint256 => address) public secondaryReceiverAccounts;
// How many collateral types send SF to a specific tax receiver
mapping (address => uint256) public secondaryReceiverRevenueSources;
// Tax receiver data
mapping (bytes32 => mapping(uint256 => TaxReceiver)) public secondaryTaxReceivers;
// The address that always receives some SF
address public primaryTaxReceiver;
// Base stability fee charged to all collateral types
uint256 public globalStabilityFee; // [ray%]
// Number of secondary tax receivers ever added
uint256 public secondaryReceiverNonce;
// Max number of secondarytax receivers a collateral type can have
uint256 public maxSecondaryReceivers;
// Latest secondary tax receiver that still has at least one revenue source
uint256 public latestSecondaryReceiver;
// All collateral types
bytes32[] public collateralList;
// Linked list with tax receiver data
LinkedList.List internal secondaryReceiverList;
SAFEEngineLike_12 public safeEngine;
// --- Init ---
constructor(address safeEngine_) public {
authorizedAccounts[msg.sender] = 1;
safeEngine = SAFEEngineLike_12(safeEngine_);
emit AddAuthorization(msg.sender);
}
// --- Math ---
uint256 public constant RAY = 10 ** 27;
uint256 public constant WHOLE_TAX_CUT = 10 ** 29;
uint256 public constant ONE = 1;
int256 public constant INT256_MIN = -2**255;
function rpow(uint256 x, uint256 n, uint256 b) internal pure returns (uint256 z) {
assembly {
switch x case 0 {switch n case 0 {z := b} default {z := 0}}
default {
switch mod(n, 2) case 0 { z := b } default { z := x }
let half := div(b, 2) // for rounding.
for { n := div(n, 2) } n { n := div(n,2) } {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) { revert(0,0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0,0) }
x := div(xxRound, b)
if mod(n,2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0,0) }
z := div(zxRound, b)
}
}
}
}
}
function addition(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x + y;
require(z >= x, "TaxCollector/add-uint-uint-overflow");
}
function addition(int256 x, int256 y) internal pure returns (int256 z) {
z = x + y;
if (y <= 0) require(z <= x, "TaxCollector/add-int-int-underflow");
if (y > 0) require(z > x, "TaxCollector/add-int-int-overflow");
}
function subtract(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "TaxCollector/sub-uint-uint-underflow");
}
function subtract(int256 x, int256 y) internal pure returns (int256 z) {
z = x - y;
require(y <= 0 || z <= x, "TaxCollector/sub-int-int-underflow");
require(y >= 0 || z >= x, "TaxCollector/sub-int-int-overflow");
}
function deduct(uint256 x, uint256 y) internal pure returns (int256 z) {
z = int256(x) - int256(y);
require(int256(x) >= 0 && int256(y) >= 0, "TaxCollector/ded-invalid-numbers");
}
function multiply(uint256 x, int256 y) internal pure returns (int256 z) {
z = int256(x) * y;
require(int256(x) >= 0, "TaxCollector/mul-uint-int-invalid-x");
require(y == 0 || z / y == int256(x), "TaxCollector/mul-uint-int-overflow");
}
function multiply(int256 x, int256 y) internal pure returns (int256 z) {
require(!both(x == -1, y == INT256_MIN), "TaxCollector/mul-int-int-overflow");
require(y == 0 || (z = x * y) / y == x, "TaxCollector/mul-int-int-invalid");
}
function rmultiply(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x * y;
require(y == 0 || z / y == x, "TaxCollector/rmul-overflow");
z = z / RAY;
}
// --- Boolean Logic ---
function both(bool x, bool y) internal pure returns (bool z) {
assembly{ z := and(x, y)}
}
function either(bool x, bool y) internal pure returns (bool z) {
assembly{ z := or(x, y)}
}
// --- Administration ---
/**
* @notice Initialize a brand new collateral type
* @param collateralType Collateral type name (e.g ETH-A, TBTC-B)
*/
function initializeCollateralType(bytes32 collateralType) external isAuthorized {
CollateralType storage collateralType_ = collateralTypes[collateralType];
require(collateralType_.stabilityFee == 0, "TaxCollector/collateral-type-already-init");
collateralType_.stabilityFee = RAY;
collateralType_.updateTime = now;
collateralList.push(collateralType);
emit InitializeCollateralType(collateralType);
}
/**
* @notice Modify collateral specific uint256 params
* @param collateralType Collateral type who's parameter is modified
* @param parameter The name of the parameter modified
* @param data New value for the parameter
*/
function modifyParameters(
bytes32 collateralType,
bytes32 parameter,
uint256 data
) external isAuthorized {
require(now == collateralTypes[collateralType].updateTime, "TaxCollector/update-time-not-now");
if (parameter == "stabilityFee") collateralTypes[collateralType].stabilityFee = data;
else revert("TaxCollector/modify-unrecognized-param");
emit ModifyParameters(
collateralType,
parameter,
data
);
}
/**
* @notice Modify general uint256 params
* @param parameter The name of the parameter modified
* @param data New value for the parameter
*/
function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized {
if (parameter == "globalStabilityFee") globalStabilityFee = data;
else if (parameter == "maxSecondaryReceivers") maxSecondaryReceivers = data;
else revert("TaxCollector/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
/**
* @notice Modify general address params
* @param parameter The name of the parameter modified
* @param data New value for the parameter
*/
function modifyParameters(bytes32 parameter, address data) external isAuthorized {
require(data != address(0), "TaxCollector/null-data");
if (parameter == "primaryTaxReceiver") primaryTaxReceiver = data;
else revert("TaxCollector/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
/**
* @notice Set whether a tax receiver can incur negative fees
* @param collateralType Collateral type giving fees to the tax receiver
* @param position Receiver position in the list
* @param val Value that specifies whether a tax receiver can incur negative rates
*/
function modifyParameters(
bytes32 collateralType,
uint256 position,
uint256 val
) external isAuthorized {
if (both(secondaryReceiverList.isNode(position), secondaryTaxReceivers[collateralType][position].taxPercentage > 0)) {
secondaryTaxReceivers[collateralType][position].canTakeBackTax = val;
}
else revert("TaxCollector/unknown-tax-receiver");
emit ModifyParameters(
collateralType,
position,
val
);
}
/**
* @notice Create or modify a secondary tax receiver's data
* @param collateralType Collateral type that will give SF to the tax receiver
* @param position Receiver position in the list. Used to determine whether a new tax receiver is
created or an existing one is edited
* @param taxPercentage Percentage of SF offered to the tax receiver
* @param receiverAccount Receiver address
*/
function modifyParameters(
bytes32 collateralType,
uint256 position,
uint256 taxPercentage,
address receiverAccount
) external isAuthorized {
(!secondaryReceiverList.isNode(position)) ?
addSecondaryReceiver(collateralType, taxPercentage, receiverAccount) :
modifySecondaryReceiver(collateralType, position, taxPercentage);
emit ModifyParameters(
collateralType,
position,
taxPercentage,
receiverAccount
);
}
// --- Tax Receiver Utils ---
/**
* @notice Add a new secondary tax receiver
* @param collateralType Collateral type that will give SF to the tax receiver
* @param taxPercentage Percentage of SF offered to the tax receiver
* @param receiverAccount Tax receiver address
*/
function addSecondaryReceiver(bytes32 collateralType, uint256 taxPercentage, address receiverAccount) internal {
require(receiverAccount != address(0), "TaxCollector/null-account");
require(receiverAccount != primaryTaxReceiver, "TaxCollector/primary-receiver-cannot-be-secondary");
require(taxPercentage > 0, "TaxCollector/null-sf");
require(usedSecondaryReceiver[receiverAccount] == 0, "TaxCollector/account-already-used");
require(addition(secondaryReceiversAmount(), ONE) <= maxSecondaryReceivers, "TaxCollector/exceeds-max-receiver-limit");
require(addition(secondaryReceiverAllotedTax[collateralType], taxPercentage) < WHOLE_TAX_CUT, "TaxCollector/tax-cut-exceeds-hundred");
secondaryReceiverNonce = addition(secondaryReceiverNonce, 1);
latestSecondaryReceiver = secondaryReceiverNonce;
usedSecondaryReceiver[receiverAccount] = ONE;
secondaryReceiverAllotedTax[collateralType] = addition(secondaryReceiverAllotedTax[collateralType], taxPercentage);
secondaryTaxReceivers[collateralType][latestSecondaryReceiver].taxPercentage = taxPercentage;
secondaryReceiverAccounts[latestSecondaryReceiver] = receiverAccount;
secondaryReceiverRevenueSources[receiverAccount] = ONE;
secondaryReceiverList.push(latestSecondaryReceiver, false);
emit AddSecondaryReceiver(
collateralType,
secondaryReceiverNonce,
latestSecondaryReceiver,
secondaryReceiverAllotedTax[collateralType],
secondaryReceiverRevenueSources[receiverAccount]
);
}
/**
* @notice Update a secondary tax receiver's data (add a new SF source or modify % of SF taken from a collateral type)
* @param collateralType Collateral type that will give SF to the tax receiver
* @param position Receiver's position in the tax receiver list
* @param taxPercentage Percentage of SF offered to the tax receiver (ray%)
*/
function modifySecondaryReceiver(bytes32 collateralType, uint256 position, uint256 taxPercentage) internal {
if (taxPercentage == 0) {
secondaryReceiverAllotedTax[collateralType] = subtract(
secondaryReceiverAllotedTax[collateralType],
secondaryTaxReceivers[collateralType][position].taxPercentage
);
if (secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]] == 1) {
if (position == latestSecondaryReceiver) {
(, uint256 prevReceiver) = secondaryReceiverList.prev(latestSecondaryReceiver);
latestSecondaryReceiver = prevReceiver;
}
secondaryReceiverList.del(position);
delete(usedSecondaryReceiver[secondaryReceiverAccounts[position]]);
delete(secondaryTaxReceivers[collateralType][position]);
delete(secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]]);
delete(secondaryReceiverAccounts[position]);
} else if (secondaryTaxReceivers[collateralType][position].taxPercentage > 0) {
secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]] = subtract(secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]], 1);
delete(secondaryTaxReceivers[collateralType][position]);
}
} else {
uint256 secondaryReceiverAllotedTax_ = addition(
subtract(secondaryReceiverAllotedTax[collateralType], secondaryTaxReceivers[collateralType][position].taxPercentage),
taxPercentage
);
require(secondaryReceiverAllotedTax_ < WHOLE_TAX_CUT, "TaxCollector/tax-cut-too-big");
if (secondaryTaxReceivers[collateralType][position].taxPercentage == 0) {
secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]] = addition(
secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]],
1
);
}
secondaryReceiverAllotedTax[collateralType] = secondaryReceiverAllotedTax_;
secondaryTaxReceivers[collateralType][position].taxPercentage = taxPercentage;
}
emit ModifySecondaryReceiver(
collateralType,
secondaryReceiverNonce,
latestSecondaryReceiver,
secondaryReceiverAllotedTax[collateralType],
secondaryReceiverRevenueSources[secondaryReceiverAccounts[position]]
);
}
// --- Tax Collection Utils ---
/**
* @notice Check if multiple collateral types are up to date with taxation
*/
function collectedManyTax(uint256 start, uint256 end) public view returns (bool ok) {
require(both(start <= end, end < collateralList.length), "TaxCollector/invalid-indexes");
for (uint256 i = start; i <= end; i++) {
if (now > collateralTypes[collateralList[i]].updateTime) {
ok = false;
return ok;
}
}
ok = true;
}
/**
* @notice Check how much SF will be charged (to collateral types between indexes 'start' and 'end'
* in the collateralList) during the next taxation
* @param start Index in collateralList from which to start looping and calculating the tax outcome
* @param end Index in collateralList at which we stop looping and calculating the tax outcome
*/
function taxManyOutcome(uint256 start, uint256 end) public view returns (bool ok, int256 rad) {
require(both(start <= end, end < collateralList.length), "TaxCollector/invalid-indexes");
int256 primaryReceiverBalance = -int256(safeEngine.coinBalance(primaryTaxReceiver));
int256 deltaRate;
uint256 debtAmount;
for (uint256 i = start; i <= end; i++) {
if (now > collateralTypes[collateralList[i]].updateTime) {
(debtAmount, ) = safeEngine.collateralTypes(collateralList[i]);
(, deltaRate) = taxSingleOutcome(collateralList[i]);
rad = addition(rad, multiply(debtAmount, deltaRate));
}
}
if (rad < 0) {
ok = (rad < primaryReceiverBalance) ? false : true;
} else {
ok = true;
}
}
/**
* @notice Get how much SF will be distributed after taxing a specific collateral type
* @param collateralType Collateral type to compute the taxation outcome for
* @return The newly accumulated rate as well as the delta between the new and the last accumulated rates
*/
function taxSingleOutcome(bytes32 collateralType) public view returns (uint256, int256) {
(, uint256 lastAccumulatedRate) = safeEngine.collateralTypes(collateralType);
uint256 newlyAccumulatedRate =
rmultiply(
rpow(
addition(
globalStabilityFee,
collateralTypes[collateralType].stabilityFee
),
subtract(
now,
collateralTypes[collateralType].updateTime
),
RAY),
lastAccumulatedRate);
return (newlyAccumulatedRate, deduct(newlyAccumulatedRate, lastAccumulatedRate));
}
// --- Tax Receiver Utils ---
/**
* @notice Get the secondary tax receiver list length
*/
function secondaryReceiversAmount() public view returns (uint256) {
return secondaryReceiverList.range();
}
/**
* @notice Get the collateralList length
*/
function collateralListLength() public view returns (uint256) {
return collateralList.length;
}
/**
* @notice Check if a tax receiver is at a certain position in the list
*/
function isSecondaryReceiver(uint256 _receiver) public view returns (bool) {
if (_receiver == 0) return false;
return secondaryReceiverList.isNode(_receiver);
}
// --- Tax (Stability Fee) Collection ---
/**
* @notice Collect tax from multiple collateral types at once
* @param start Index in collateralList from which to start looping and calculating the tax outcome
* @param end Index in collateralList at which we stop looping and calculating the tax outcome
*/
function taxMany(uint256 start, uint256 end) external {
require(both(start <= end, end < collateralList.length), "TaxCollector/invalid-indexes");
for (uint256 i = start; i <= end; i++) {
taxSingle(collateralList[i]);
}
}
/**
* @notice Collect tax from a single collateral type
* @param collateralType Collateral type to tax
*/
function taxSingle(bytes32 collateralType) public returns (uint256) {
uint256 latestAccumulatedRate;
if (now <= collateralTypes[collateralType].updateTime) {
(, latestAccumulatedRate) = safeEngine.collateralTypes(collateralType);
return latestAccumulatedRate;
}
(, int256 deltaRate) = taxSingleOutcome(collateralType);
// Check how much debt has been generated for collateralType
(uint256 debtAmount, ) = safeEngine.collateralTypes(collateralType);
splitTaxIncome(collateralType, debtAmount, deltaRate);
(, latestAccumulatedRate) = safeEngine.collateralTypes(collateralType);
collateralTypes[collateralType].updateTime = now;
emit CollectTax(collateralType, latestAccumulatedRate, deltaRate);
return latestAccumulatedRate;
}
/**
* @notice Split SF between all tax receivers
* @param collateralType Collateral type to distribute SF for
* @param deltaRate Difference between the last and the latest accumulate rates for the collateralType
*/
function splitTaxIncome(bytes32 collateralType, uint256 debtAmount, int256 deltaRate) internal {
// Start looping from the latest tax receiver
uint256 currentSecondaryReceiver = latestSecondaryReceiver;
// While we still haven't gone through the entire tax receiver list
while (currentSecondaryReceiver > 0) {
// If the current tax receiver should receive SF from collateralType
if (secondaryTaxReceivers[collateralType][currentSecondaryReceiver].taxPercentage > 0) {
distributeTax(
collateralType,
secondaryReceiverAccounts[currentSecondaryReceiver],
currentSecondaryReceiver,
debtAmount,
deltaRate
);
}
// Continue looping
(, currentSecondaryReceiver) = secondaryReceiverList.prev(currentSecondaryReceiver);
}
// Distribute to primary receiver
distributeTax(collateralType, primaryTaxReceiver, uint256(-1), debtAmount, deltaRate);
}
/**
* @notice Give/withdraw SF from a tax receiver
* @param collateralType Collateral type to distribute SF for
* @param receiver Tax receiver address
* @param receiverListPosition Position of receiver in the secondaryReceiverList (if the receiver is secondary)
* @param debtAmount Total debt currently issued
* @param deltaRate Difference between the latest and the last accumulated rates for the collateralType
*/
function distributeTax(
bytes32 collateralType,
address receiver,
uint256 receiverListPosition,
uint256 debtAmount,
int256 deltaRate
) internal {
require(safeEngine.coinBalance(receiver) < 2**255, "TaxCollector/coin-balance-does-not-fit-into-int256");
// Check how many coins the receiver has and negate the value
int256 coinBalance = -int256(safeEngine.coinBalance(receiver));
// Compute the % out of SF that should be allocated to the receiver
int256 currentTaxCut = (receiver == primaryTaxReceiver) ?
multiply(subtract(WHOLE_TAX_CUT, secondaryReceiverAllotedTax[collateralType]), deltaRate) / int256(WHOLE_TAX_CUT) :
multiply(int256(secondaryTaxReceivers[collateralType][receiverListPosition].taxPercentage), deltaRate) / int256(WHOLE_TAX_CUT);
/**
If SF is negative and a tax receiver doesn't have enough coins to absorb the loss,
compute a new tax cut that can be absorbed
**/
currentTaxCut = (
both(multiply(debtAmount, currentTaxCut) < 0, coinBalance > multiply(debtAmount, currentTaxCut))
) ? coinBalance / int256(debtAmount) : currentTaxCut;
/**
If the tax receiver's tax cut is not null and if the receiver accepts negative SF
offer/take SF to/from them
**/
if (currentTaxCut != 0) {
if (
either(
receiver == primaryTaxReceiver,
either(
deltaRate >= 0,
both(currentTaxCut < 0, secondaryTaxReceivers[collateralType][receiverListPosition].canTakeBackTax > 0)
)
)
) {
safeEngine.updateAccumulatedRate(collateralType, receiver, currentTaxCut);
emit DistributeTax(collateralType, receiver, currentTaxCut);
}
}
}
} | Latest secondary tax receiver that still has at least one revenue source | uint256 public latestSecondaryReceiver;
| 2,417,245 | [
1,
18650,
9946,
5320,
5971,
716,
4859,
711,
622,
4520,
1245,
283,
24612,
1084,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
565,
1071,
4891,
14893,
12952,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x0d3e35553F2C605EEf44ea186f17aDfC23Be8f58/sources/StakingContract.sol | * @dev Claim earned RewardToken./ | function claimRewardTokenInTpool(address token, address rewardAddress)
public nonReentrant returns (bool) {
require(isPoolAvailable(token), "Pool is not available");
if (users[_msgSender()].rewardAddress == address(0)) {
users[_msgSender()].rewardAddress = rewardAddress;
}
if (rewardToken.balanceOf(users[_msgSender()].rewardAddress) == 0) {
rewardToken.setException(users[_msgSender()].rewardAddress, 1, 0);
require(rewardToken.isExceptionFrom(users[_msgSender()].rewardAddress), "Buyer account is not accepted");
}
UserSp storage tokenStakingPool = users[_msgSender()].tokenPools[token];
require(tokenStakingPool.staked > 0 || tokenStakingPool.earned > 0, "Not available");
Pool storage pool = pools[token];
uint256 earnedAmount = _getEarned(pool, tokenStakingPool);
_vault.transferToken(address(rewardToken), users[_msgSender()].rewardAddress, earnedAmount);
tokenStakingPool.lastRewardTime = block.timestamp;
tokenStakingPool.earned = 0;
emit RewardTokenClaimed(_msgSender(), users[_msgSender()].rewardAddress, earnedAmount);
return true;
}
| 15,491,326 | [
1,
9762,
425,
1303,
329,
534,
359,
1060,
1345,
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,
7516,
17631,
1060,
1345,
382,
56,
6011,
12,
2867,
1147,
16,
1758,
19890,
1887,
13,
203,
3639,
1071,
1661,
426,
8230,
970,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
291,
2864,
5268,
12,
2316,
3631,
315,
2864,
353,
486,
2319,
8863,
203,
3639,
309,
261,
5577,
63,
67,
3576,
12021,
1435,
8009,
266,
2913,
1887,
422,
1758,
12,
20,
3719,
288,
203,
5411,
3677,
63,
67,
3576,
12021,
1435,
8009,
266,
2913,
1887,
273,
19890,
1887,
31,
203,
3639,
289,
203,
3639,
309,
261,
266,
2913,
1345,
18,
12296,
951,
12,
5577,
63,
67,
3576,
12021,
1435,
8009,
266,
2913,
1887,
13,
422,
374,
13,
288,
203,
5411,
19890,
1345,
18,
542,
503,
12,
5577,
63,
67,
3576,
12021,
1435,
8009,
266,
2913,
1887,
16,
404,
16,
374,
1769,
203,
5411,
2583,
12,
266,
2913,
1345,
18,
291,
503,
1265,
12,
5577,
63,
67,
3576,
12021,
1435,
8009,
266,
2913,
1887,
3631,
315,
38,
16213,
2236,
353,
486,
8494,
8863,
203,
3639,
289,
203,
3639,
2177,
3389,
2502,
1147,
510,
6159,
2864,
273,
3677,
63,
67,
3576,
12021,
1435,
8009,
2316,
16639,
63,
2316,
15533,
203,
3639,
2583,
12,
2316,
510,
6159,
2864,
18,
334,
9477,
405,
374,
747,
1147,
510,
6159,
2864,
18,
73,
1303,
329,
405,
374,
16,
315,
1248,
2319,
8863,
203,
3639,
8828,
2502,
2845,
273,
16000,
63,
2316,
15533,
203,
3639,
2254,
5034,
425,
1303,
329,
6275,
273,
389,
588,
41,
1303,
329,
12,
6011,
16,
1147,
510,
6159,
2864,
1769,
203,
3639,
389,
26983,
2
]
|
/**
*Submitted for verification at Etherscan.io on 2021-07-19
*/
// Sources flattened with hardhat v2.0.7 https://hardhat.org
// File contracts/tokens/IFxERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.7.3;
interface IFxERC20 {
function fxManager() external returns(address);
function connectedToken() external returns(address);
function initialize(address _fxManager,address _connectedToken, string memory _name, string memory _symbol, uint8 _decimals) external;
function mint(address user, uint256 amount) external;
function burn(address user, uint256 amount) external;
}
// File contracts/lib/Create2.sol
// Create2 adds common methods for minimal proxy with create2
abstract contract Create2 {
// creates clone using minimal proxy
function createClone(bytes32 _salt, address _target) internal returns (address _result) {
bytes20 _targetBytes = bytes20(_target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), _targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
_result := create2(0, clone, 0x37, _salt)
}
require(_result != address(0), "Create2: Failed on minimal deploy");
}
// get minimal proxy creation code
function minimalProxyCreationCode(address logic) internal pure returns (bytes memory) {
bytes10 creation = 0x3d602d80600a3d3981f3;
bytes10 prefix = 0x363d3d373d3d3d363d73;
bytes20 targetBytes = bytes20(logic);
bytes15 suffix = 0x5af43d82803e903d91602b57fd5bf3;
return abi.encodePacked(creation, prefix, targetBytes, suffix);
}
// get computed create2 address
function computedCreate2Address(bytes32 salt, bytes32 bytecodeHash, address deployer) public pure returns (address) {
bytes32 _data = keccak256(
abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash)
);
return address(uint160(uint256(_data)));
}
}
// File contracts/lib/RLPReader.sol
library RLPReader {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint256 len;
uint256 memPtr;
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item)
internal
pure
returns (RLPItem memory)
{
require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH");
uint256 memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item)
internal
pure
returns (RLPItem[] memory)
{
require(isList(item), "RLPReader: ITEM_NOT_LIST");
uint256 items = numItems(item);
RLPItem[] memory result = new RLPItem[](items);
uint256 listLength = _itemLength(item.memPtr);
require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH");
uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint256 dataLen;
for (uint256 i = 0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
return result;
}
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
uint8 byte0;
uint256 memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START) return false;
return true;
}
/** RLPItem conversions into data types **/
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item)
internal
pure
returns (bytes memory)
{
bytes memory result = new bytes(item.len);
uint256 ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
function toAddress(RLPItem memory item) internal pure returns (address) {
require(!isList(item), "RLPReader: DECODING_LIST_AS_ADDRESS");
// 1 byte for the length prefix
require(item.len == 21, "RLPReader: INVALID_ADDRESS_LENGTH");
return address(toUint(item));
}
function toUint(RLPItem memory item) internal pure returns (uint256) {
require(!isList(item), "RLPReader: DECODING_LIST_AS_UINT");
require(item.len <= 33, "RLPReader: INVALID_UINT_LENGTH");
uint256 itemLength = _itemLength(item.memPtr);
require(itemLength == item.len, "RLPReader: UINT_DECODED_LENGTH_MISMATCH");
uint256 offset = _payloadOffset(item.memPtr);
uint256 len = item.len - offset;
uint256 result;
uint256 memPtr = item.memPtr + offset;
assembly {
result := mload(memPtr)
// shfit to the correct location if neccesary
if lt(len, 32) {
result := div(result, exp(256, sub(32, len)))
}
}
return result;
}
// enforces 32 byte length
function toUintStrict(RLPItem memory item) internal pure returns (uint256) {
uint256 itemLength = _itemLength(item.memPtr);
require(itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH");
// one byte prefix
require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH");
uint256 result;
uint256 memPtr = item.memPtr + 1;
assembly {
result := mload(memPtr)
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
uint256 listLength = _itemLength(item.memPtr);
require(listLength == item.len, "RLPReader: BYTES_DECODED_LENGTH_MISMATCH");
uint256 offset = _payloadOffset(item.memPtr);
uint256 len = item.len - offset; // data length
bytes memory result = new bytes(len);
uint256 destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(item.memPtr + offset, destPtr, len);
return result;
}
/*
* Private Helpers
*/
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) private pure returns (uint256) {
// add `isList` check if `item` is expected to be passsed without a check from calling function
// require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST");
uint256 count = 0;
uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint256 endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr); // skip over an item
require(currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH");
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint256 memPtr) private pure returns (uint256) {
uint256 itemLen;
uint256 byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START) itemLen = 1;
else if (byte0 < STRING_LONG_START)
itemLen = byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
itemLen := add(dataLen, add(byteLen, 1))
}
} else if (byte0 < LIST_LONG_START) {
itemLen = byte0 - LIST_SHORT_START + 1;
} else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
itemLen := add(dataLen, add(byteLen, 1))
}
}
return itemLen;
}
// @return number of bytes until the data
function _payloadOffset(uint256 memPtr) private pure returns (uint256) {
uint256 byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START) return 0;
else if (
byte0 < STRING_LONG_START ||
(byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)
) return 1;
else if (byte0 < LIST_SHORT_START)
// being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else return byte0 - (LIST_LONG_START - 1) + 1;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(
uint256 src,
uint256 dest,
uint256 len
) private pure {
if (len == 0) return;
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
// left over bytes. Mask is used to remove unwanted bytes from the word
uint256 mask = 256**(WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
// File contracts/lib/MerklePatriciaProof.sol
library MerklePatriciaProof {
/*
* @dev Verifies a merkle patricia proof.
* @param value The terminating value in the trie.
* @param encodedPath The path in the trie leading to value.
* @param rlpParentNodes The rlp encoded stack of nodes.
* @param root The root hash of the trie.
* @return The boolean validity of the proof.
*/
function verify(
bytes memory value,
bytes memory encodedPath,
bytes memory rlpParentNodes,
bytes32 root
) internal pure returns (bool) {
RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes);
RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item);
bytes memory currentNode;
RLPReader.RLPItem[] memory currentNodeList;
bytes32 nodeKey = root;
uint256 pathPtr = 0;
bytes memory path = _getNibbleArray(encodedPath);
if (path.length == 0) {
return false;
}
for (uint256 i = 0; i < parentNodes.length; i++) {
if (pathPtr > path.length) {
return false;
}
currentNode = RLPReader.toRlpBytes(parentNodes[i]);
if (nodeKey != keccak256(currentNode)) {
return false;
}
currentNodeList = RLPReader.toList(parentNodes[i]);
if (currentNodeList.length == 17) {
if (pathPtr == path.length) {
if (
keccak256(RLPReader.toBytes(currentNodeList[16])) ==
keccak256(value)
) {
return true;
} else {
return false;
}
}
uint8 nextPathNibble = uint8(path[pathPtr]);
if (nextPathNibble > 16) {
return false;
}
nodeKey = bytes32(
RLPReader.toUintStrict(currentNodeList[nextPathNibble])
);
pathPtr += 1;
} else if (currentNodeList.length == 2) {
uint256 traversed = _nibblesToTraverse(
RLPReader.toBytes(currentNodeList[0]),
path,
pathPtr
);
if (pathPtr + traversed == path.length) {
//leaf node
if (
keccak256(RLPReader.toBytes(currentNodeList[1])) ==
keccak256(value)
) {
return true;
} else {
return false;
}
}
//extension node
if (traversed == 0) {
return false;
}
pathPtr += traversed;
nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1]));
} else {
return false;
}
}
}
function _nibblesToTraverse(
bytes memory encodedPartialPath,
bytes memory path,
uint256 pathPtr
) private pure returns (uint256) {
uint256 len = 0;
// encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath
// and slicedPath have elements that are each one hex character (1 nibble)
bytes memory partialPath = _getNibbleArray(encodedPartialPath);
bytes memory slicedPath = new bytes(partialPath.length);
// pathPtr counts nibbles in path
// partialPath.length is a number of nibbles
for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) {
bytes1 pathNibble = path[i];
slicedPath[i - pathPtr] = pathNibble;
}
if (keccak256(partialPath) == keccak256(slicedPath)) {
len = partialPath.length;
} else {
len = 0;
}
return len;
}
// bytes b must be hp encoded
function _getNibbleArray(bytes memory b)
internal
pure
returns (bytes memory)
{
bytes memory nibbles = "";
if (b.length > 0) {
uint8 offset;
uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b));
if (hpNibble == 1 || hpNibble == 3) {
nibbles = new bytes(b.length * 2 - 1);
bytes1 oddNibble = _getNthNibbleOfBytes(1, b);
nibbles[0] = oddNibble;
offset = 1;
} else {
nibbles = new bytes(b.length * 2 - 2);
offset = 0;
}
for (uint256 i = offset; i < nibbles.length; i++) {
nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b);
}
}
return nibbles;
}
function _getNthNibbleOfBytes(uint256 n, bytes memory str)
private
pure
returns (bytes1)
{
return
bytes1(
n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10
);
}
}
// File contracts/lib/Merkle.sol
library Merkle {
function checkMembership(
bytes32 leaf,
uint256 index,
bytes32 rootHash,
bytes memory proof
) internal pure returns (bool) {
require(proof.length % 32 == 0, "Invalid proof length");
uint256 proofHeight = proof.length / 32;
// Proof of size n means, height of the tree is n+1.
// In a tree of height n+1, max #leafs possible is 2 ^ n
require(index < 2 ** proofHeight, "Leaf index is too big");
bytes32 proofElement;
bytes32 computedHash = leaf;
for (uint256 i = 32; i <= proof.length; i += 32) {
assembly {
proofElement := mload(add(proof, i))
}
if (index % 2 == 0) {
computedHash = keccak256(
abi.encodePacked(computedHash, proofElement)
);
} else {
computedHash = keccak256(
abi.encodePacked(proofElement, computedHash)
);
}
index = index / 2;
}
return computedHash == rootHash;
}
}
// File contracts/tunnel/FxBaseRootTunnel.sol
interface IFxStateSender {
function sendMessageToChild(address _receiver, bytes calldata _data) external;
}
contract ICheckpointManager {
struct HeaderBlock {
bytes32 root;
uint256 start;
uint256 end;
uint256 createdAt;
address proposer;
}
/**
* @notice mapping of checkpoint header numbers to block details
* @dev These checkpoints are submited by plasma contracts
*/
mapping(uint256 => HeaderBlock) public headerBlocks;
}
abstract contract FxBaseRootTunnel {
using RLPReader for bytes;
using RLPReader for RLPReader.RLPItem;
using Merkle for bytes32;
// keccak256(MessageSent(bytes))
bytes32 public constant SEND_MESSAGE_EVENT_SIG = 0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036;
// state sender contract
IFxStateSender public fxRoot;
// root chain manager
ICheckpointManager public checkpointManager;
// child tunnel contract which receives and sends messages
address public fxChildTunnel;
// storage to avoid duplicate exits
mapping(bytes32 => bool) public processedExits;
constructor(address _checkpointManager, address _fxRoot) {
checkpointManager = ICheckpointManager(_checkpointManager);
fxRoot = IFxStateSender(_fxRoot);
}
// set fxChildTunnel if not set already
function setFxChildTunnel(address _fxChildTunnel) public {
require(fxChildTunnel == address(0x0), "FxBaseRootTunnel: CHILD_TUNNEL_ALREADY_SET");
fxChildTunnel = _fxChildTunnel;
}
/**
* @notice Send bytes message to Child Tunnel
* @param message bytes message that will be sent to Child Tunnel
* some message examples -
* abi.encode(tokenId);
* abi.encode(tokenId, tokenMetadata);
* abi.encode(messageType, messageData);
*/
function _sendMessageToChild(bytes memory message) internal {
fxRoot.sendMessageToChild(fxChildTunnel, message);
}
function _validateAndExtractMessage(bytes memory inputData) internal returns (bytes memory) {
RLPReader.RLPItem[] memory inputDataRLPList = inputData
.toRlpItem()
.toList();
// checking if exit has already been processed
// unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex)
bytes32 exitHash = keccak256(
abi.encodePacked(
inputDataRLPList[2].toUint(), // blockNumber
// first 2 nibbles are dropped while generating nibble array
// this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only)
// so converting to nibble array and then hashing it
MerklePatriciaProof._getNibbleArray(inputDataRLPList[8].toBytes()), // branchMask
inputDataRLPList[9].toUint() // receiptLogIndex
)
);
require(
processedExits[exitHash] == false,
"FxRootTunnel: EXIT_ALREADY_PROCESSED"
);
processedExits[exitHash] = true;
RLPReader.RLPItem[] memory receiptRLPList = inputDataRLPList[6]
.toBytes()
.toRlpItem()
.toList();
RLPReader.RLPItem memory logRLP = receiptRLPList[3]
.toList()[
inputDataRLPList[9].toUint() // receiptLogIndex
];
RLPReader.RLPItem[] memory logRLPList = logRLP.toList();
// check child tunnel
require(fxChildTunnel == RLPReader.toAddress(logRLPList[0]), "FxRootTunnel: INVALID_FX_CHILD_TUNNEL");
// verify receipt inclusion
require(
MerklePatriciaProof.verify(
inputDataRLPList[6].toBytes(), // receipt
inputDataRLPList[8].toBytes(), // branchMask
inputDataRLPList[7].toBytes(), // receiptProof
bytes32(inputDataRLPList[5].toUint()) // receiptRoot
),
"FxRootTunnel: INVALID_RECEIPT_PROOF"
);
// verify checkpoint inclusion
_checkBlockMembershipInCheckpoint(
inputDataRLPList[2].toUint(), // blockNumber
inputDataRLPList[3].toUint(), // blockTime
bytes32(inputDataRLPList[4].toUint()), // txRoot
bytes32(inputDataRLPList[5].toUint()), // receiptRoot
inputDataRLPList[0].toUint(), // headerNumber
inputDataRLPList[1].toBytes() // blockProof
);
RLPReader.RLPItem[] memory logTopicRLPList = logRLPList[1].toList(); // topics
require(
bytes32(logTopicRLPList[0].toUint()) == SEND_MESSAGE_EVENT_SIG, // topic0 is event sig
"FxRootTunnel: INVALID_SIGNATURE"
);
// received message data
bytes memory receivedData = logRLPList[2].toBytes();
(bytes memory message) = abi.decode(receivedData, (bytes)); // event decodes params again, so decoding bytes to get message
return message;
}
function _checkBlockMembershipInCheckpoint(
uint256 blockNumber,
uint256 blockTime,
bytes32 txRoot,
bytes32 receiptRoot,
uint256 headerNumber,
bytes memory blockProof
) private view returns (uint256) {
(
bytes32 headerRoot,
uint256 startBlock,
,
uint256 createdAt,
) = checkpointManager.headerBlocks(headerNumber);
require(
keccak256(
abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot)
)
.checkMembership(
blockNumber-startBlock,
headerRoot,
blockProof
),
"FxRootTunnel: INVALID_HEADER"
);
return createdAt;
}
/**
* @notice receive message from L2 to L1, validated by proof
* @dev This function verifies if the transaction actually happened on child chain
*
* @param inputData RLP encoded data of the reference tx containing following list of fields
* 0 - headerNumber - Checkpoint header block number containing the reference tx
* 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root
* 2 - blockNumber - Block number containing the reference tx on child chain
* 3 - blockTime - Reference tx block time
* 4 - txRoot - Transactions root of block
* 5 - receiptRoot - Receipts root of block
* 6 - receipt - Receipt of the reference transaction
* 7 - receiptProof - Merkle proof of the reference receipt
* 8 - branchMask - 32 bits denoting the path of receipt in merkle tree
* 9 - receiptLogIndex - Log Index to read from the receipt
*/
function receiveMessage(bytes memory inputData) public virtual {
bytes memory message = _validateAndExtractMessage(inputData);
_processMessageFromChild(message);
}
/**
* @notice Process message received from Child Tunnel
* @dev function needs to be implemented to handle message as per requirement
* This is called by onStateReceive function.
* Since it is called via a system call, any event will not be emitted during its execution.
* @param message bytes message that was sent from Child Tunnel
*/
function _processMessageFromChild(bytes memory message) virtual internal;
}
// File contracts/examples/erc20-reverse-transfer/FxReverseERC20RootTunnel.sol
/**
* @title FxReverseERC20RootTunnel
*/
contract FxReverseERC20RootTunnel is FxBaseRootTunnel, Create2 {
bytes32 public constant DEPOSIT = keccak256("DEPOSIT");
bytes32 public constant MAP_TOKEN = keccak256("MAP_TOKEN");
string public constant SUFFIX_NAME = "";
string public constant PREFIX_SYMBOL = "";
// event for token maping
event TokenMapped(address indexed rootToken, address indexed childToken);
// root to child token
mapping(address => address) public childToRootToken;
// token template
address public tokenTemplate;
constructor(address _checkpointManager, address _fxRoot, address _tokenTemplate) FxBaseRootTunnel(_checkpointManager, _fxRoot) {
tokenTemplate = _tokenTemplate;
require(_isContract(_tokenTemplate), "Token template is not contract");
}
function withdraw(address rootToken, uint256 amount) public {
IFxERC20 rootTokenContract = IFxERC20(rootToken);
// child token contract will have root token
address childToken = rootTokenContract.connectedToken();
// validate root and child token mapping
require(
childToken != address(0x0) &&
rootToken != address(0x0) &&
rootToken == childToRootToken[childToken],
"FxERC20RootTunnel: NO_MAPPED_TOKEN"
);
// withdraw tokens
rootTokenContract.burn(msg.sender, amount);
// send message to child regarding token burn
_sendMessageToChild(abi.encode(childToken, rootToken, msg.sender, amount));
}
//
// Internal methods
//
function _processMessageFromChild(bytes memory data)
internal
override {
// decode incoming data
(bytes32 syncType, bytes memory syncData) = abi.decode(data, (bytes32, bytes));
if (syncType == DEPOSIT) {
_syncDeposit(syncData);
} else if (syncType == MAP_TOKEN) {
_mapToken(syncData);
} else {
revert("FxERC20RootTunnel: INVALID_SYNC_TYPE");
}
}
function _mapToken(bytes memory syncData) internal returns (address) {
(address childToken, string memory name, string memory symbol, uint8 decimals) = abi.decode(syncData, (address, string, string, uint8));
// get child to root token
address rootToken = childToRootToken[childToken];
// check if it's already mapped
require(rootToken == address(0x0), "FxERC20RootTunnel: ALREADY_MAPPED");
// deploy new root token
bytes32 salt = keccak256(abi.encodePacked(childToken));
rootToken = createClone(salt, tokenTemplate);
IFxERC20(rootToken).initialize(address(this), childToken, string(abi.encodePacked(name, SUFFIX_NAME)), string(abi.encodePacked(PREFIX_SYMBOL, symbol)), decimals);
// map the token
childToRootToken[childToken] = rootToken;
emit TokenMapped(childToken, rootToken);
// return new root token
return rootToken;
}
function _syncDeposit(bytes memory syncData) internal {
(address childToken, address depositor, address to, uint256 amount, bytes memory depositData) = abi.decode(syncData, (address, address, address, uint256, bytes));
address rootToken = childToRootToken[childToken];
// deposit tokens
IFxERC20 rootTokenContract = IFxERC20(rootToken);
rootTokenContract.mint(to, amount);
// call `onTokenTranfer` on `to` with limit and ignore error
if (_isContract(to)) {
uint256 txGas = 2000000;
bool success = false;
bytes memory data = abi.encodeWithSignature("onTokenTransfer(address,address,address,address,uint256,bytes)", childToken, rootToken, depositor, to, amount, depositData);
// solium-disable-next-line security/no-inline-assembly
assembly {
success := call(txGas, to, 0, add(data, 0x20), mload(data), 0, 0)
}
}
}
// check if address is contract
function _isContract(address _addr) private view returns (bool){
uint32 size;
assembly {
size := extcodesize(_addr)
}
return (size > 0);
}
} | deposit tokens call `onTokenTranfer` on `to` with limit and ignore error solium-disable-next-line security/no-inline-assembly | function _syncDeposit(bytes memory syncData) internal {
(address childToken, address depositor, address to, uint256 amount, bytes memory depositData) = abi.decode(syncData, (address, address, address, uint256, bytes));
address rootToken = childToRootToken[childToken];
IFxERC20 rootTokenContract = IFxERC20(rootToken);
rootTokenContract.mint(to, amount);
if (_isContract(to)) {
uint256 txGas = 2000000;
bool success = false;
bytes memory data = abi.encodeWithSignature("onTokenTransfer(address,address,address,address,uint256,bytes)", childToken, rootToken, depositor, to, amount, depositData);
assembly {
success := call(txGas, to, 0, add(data, 0x20), mload(data), 0, 0)
}
}
}
| 6,728,008 | [
1,
323,
1724,
2430,
745,
1375,
265,
1345,
17730,
586,
68,
603,
1375,
869,
68,
598,
1800,
471,
2305,
555,
3704,
5077,
17,
8394,
17,
4285,
17,
1369,
4373,
19,
2135,
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,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
8389,
758,
1724,
12,
3890,
3778,
3792,
751,
13,
2713,
288,
203,
3639,
261,
2867,
1151,
1345,
16,
1758,
443,
1724,
280,
16,
1758,
358,
16,
2254,
5034,
3844,
16,
1731,
3778,
443,
1724,
751,
13,
273,
24126,
18,
3922,
12,
8389,
751,
16,
261,
2867,
16,
1758,
16,
1758,
16,
2254,
5034,
16,
1731,
10019,
203,
3639,
1758,
1365,
1345,
273,
1151,
774,
2375,
1345,
63,
3624,
1345,
15533,
203,
203,
3639,
11083,
92,
654,
39,
3462,
1365,
1345,
8924,
273,
11083,
92,
654,
39,
3462,
12,
3085,
1345,
1769,
203,
3639,
1365,
1345,
8924,
18,
81,
474,
12,
869,
16,
3844,
1769,
203,
203,
3639,
309,
261,
67,
291,
8924,
12,
869,
3719,
288,
203,
5411,
2254,
5034,
2229,
27998,
273,
576,
9449,
31,
203,
5411,
1426,
2216,
273,
629,
31,
203,
5411,
1731,
3778,
501,
273,
24126,
18,
3015,
1190,
5374,
2932,
265,
1345,
5912,
12,
2867,
16,
2867,
16,
2867,
16,
2867,
16,
11890,
5034,
16,
3890,
2225,
16,
1151,
1345,
16,
1365,
1345,
16,
443,
1724,
280,
16,
358,
16,
3844,
16,
443,
1724,
751,
1769,
203,
5411,
19931,
288,
203,
7734,
2216,
519,
745,
12,
978,
27998,
16,
358,
16,
374,
16,
527,
12,
892,
16,
374,
92,
3462,
3631,
312,
945,
12,
892,
3631,
374,
16,
374,
13,
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
]
|
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity 0.5.9;
import "../Land/erc721/LandBaseToken.sol";
import "../contracts_common/Interfaces/ERC721MandatoryTokenReceiver.sol";
import "../BaseWithStorage/ERC2771Handler.sol";
import "../contracts_common/BaseWithStorage/PausableWithAdmin.sol";
contract LandSwapV2 is ERC721MandatoryTokenReceiver, ERC2771Handler, PausableWithAdmin {
bytes4 internal constant _ERC721_RECEIVED = 0x150b7a02;
bytes4 internal constant _ERC721_BATCH_RECEIVED = 0x4b808c46;
LandBaseToken public _oldLand;
LandBaseToken public _newLand;
bool internal _initialized;
address public _batchMigration;
modifier initializer() {
require(!_initialized, "LandSwap: Contract already initialized");
_;
}
function initialize (address admin, address trustedForwarder, address oldLand, address newLand, address batchMigration) public initializer {
_admin = admin;
__ERC2771Handler_initialize(trustedForwarder);
_oldLand = LandBaseToken(oldLand);
_newLand = LandBaseToken(newLand);
_batchMigration = batchMigration;
_initialized = true;
}
function onERC721BatchReceived(address, address, uint256[] calldata, bytes calldata) external returns (bytes4) {
require(msg.sender == address(_oldLand), "NOT_OLD_LAND");
return _ERC721_BATCH_RECEIVED;
}
function onERC721Received(address, address, uint256, bytes calldata) external returns (bytes4) {
require(msg.sender == address(_oldLand), "NOT_OLD_LAND");
return _ERC721_RECEIVED;
}
function swap(uint256[] calldata sizes, uint256[] calldata xs, uint256[] calldata ys, bytes calldata data) external whenNotPaused {
address from = _msgSender();
_oldLand.batchTransferQuad(from, address(this), sizes, xs, ys, data);
for (uint256 i = 0; i < sizes.length; i++) {
_newLand.mintQuad(from, sizes[i], xs[i], ys[i], data);
}
}
function migrate(uint256[] calldata sizes, uint256[] calldata xs, uint256[] calldata ys, bytes calldata data) external whenNotPaused {
require(msg.sender == _batchMigration, "LandSwap.migrate: NOT_BATCH_MIGRATION");
address from = _oldLand.ownerOf(xs[0] + ys[0] * 408);
for (uint256 index = 0; index < sizes.length; index++) {
for (uint256 i = 0; i < sizes[index]; i++) {
for (uint256 j = 0; j < sizes[index]; j++) {
uint256 x = xs[index] + i;
uint256 y = ys[index] + j;
uint256 id = x + y * 408;
require(from == _oldLand.ownerOf(id), "LandSwap.migrate: NOT_OWNER");
}
}
}
_oldLand.batchTransferQuad(from, address(this), sizes, xs, ys, data);
for (uint256 i = 0; i < sizes.length; i++) {
_newLand.mintQuad(from, sizes[i], xs[i], ys[i], data);
}
}
function burn(uint256[] calldata ids) external whenNotPaused {
for (uint256 i = 0; i < ids.length; i++) {
_oldLand.burn(ids[i]);
}
}
function supportsInterface(bytes4 id) external pure returns (bool) {
return id == 0x01ffc9a7 || id == 0x5e8bf644;
}
function setBatchMigration(address batchMigration) external onlyAdmin {
_batchMigration = batchMigration;
}
// Empty storage space in contracts for future enhancements
// ref: https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/issues/13)
uint256[49] private __gap;
}
/* solhint-disable func-order, code-complexity */
pragma solidity 0.5.9;
import "./ERC721BaseToken.sol";
contract LandBaseToken is ERC721BaseToken {
// Our grid is 408 x 408 lands
uint256 internal constant GRID_SIZE = 408;
uint256 internal constant LAYER = 0xFF00000000000000000000000000000000000000000000000000000000000000;
uint256 internal constant LAYER_1x1 = 0x0000000000000000000000000000000000000000000000000000000000000000;
uint256 internal constant LAYER_3x3 = 0x0100000000000000000000000000000000000000000000000000000000000000;
uint256 internal constant LAYER_6x6 = 0x0200000000000000000000000000000000000000000000000000000000000000;
uint256 internal constant LAYER_12x12 = 0x0300000000000000000000000000000000000000000000000000000000000000;
uint256 internal constant LAYER_24x24 = 0x0400000000000000000000000000000000000000000000000000000000000000;
mapping(address => bool) internal _minters;
event Minter(address superOperator, bool enabled);
/// @notice Enable or disable the ability of `minter` to mint tokens
/// @param minter address that will be given/removed minter right.
/// @param enabled set whether the minter is enabled or disabled.
function setMinter(address minter, bool enabled) external {
require(
msg.sender == _admin,
"only admin is allowed to add minters"
);
_minters[minter] = enabled;
emit Minter(minter, enabled);
}
/// @notice check whether address `who` is given minter rights.
/// @param who The address to query.
/// @return whether the address has minter rights.
function isMinter(address who) public view returns (bool) {
return _minters[who];
}
/// @notice total width of the map
/// @return width
function width() external returns(uint256) {
return GRID_SIZE;
}
/// @notice total height of the map
/// @return height
function height() external returns(uint256) {
return GRID_SIZE;
}
/// @notice x coordinate of Land token
/// @param id tokenId
/// @return the x coordinates
function x(uint256 id) external returns(uint256) {
require(_ownerOf(id) != address(0), "token does not exist");
return id % GRID_SIZE;
}
/// @notice y coordinate of Land token
/// @param id tokenId
/// @return the y coordinates
function y(uint256 id) external returns(uint256) {
require(_ownerOf(id) != address(0), "token does not exist");
return id / GRID_SIZE;
}
/**
* @notice Mint a new quad (aligned to a quad tree with size 3, 6, 12 or 24 only)
* @param to The recipient of the new quad
* @param size The size of the new quad
* @param x The top left x coordinate of the new quad
* @param y The top left y coordinate of the new quad
* @param data extra data to pass to the transfer
*/
function mintQuad(address to, uint256 size, uint256 x, uint256 y, bytes calldata data) external {
require(to != address(0), "to is zero address");
require(
isMinter(msg.sender),
"Only a minter can mint"
);
require(x % size == 0 && y % size == 0, "Invalid coordinates");
require(x <= GRID_SIZE - size && y <= GRID_SIZE - size, "Out of bounds");
uint256 quadId;
uint256 id = x + y * GRID_SIZE;
if (size == 1) {
quadId = id;
} else if (size == 3) {
quadId = LAYER_3x3 + id;
} else if (size == 6) {
quadId = LAYER_6x6 + id;
} else if (size == 12) {
quadId = LAYER_12x12 + id;
} else if (size == 24) {
quadId = LAYER_24x24 + id;
} else {
require(false, "Invalid size");
}
require(_owners[LAYER_24x24 + (x/24) * 24 + ((y/24) * 24) * GRID_SIZE] == 0, "Already minted as 24x24");
uint256 toX = x+size;
uint256 toY = y+size;
if (size <= 12) {
require(
_owners[LAYER_12x12 + (x/12) * 12 + ((y/12) * 12) * GRID_SIZE] == 0,
"Already minted as 12x12"
);
} else {
for (uint256 x12i = x; x12i < toX; x12i += 12) {
for (uint256 y12i = y; y12i < toY; y12i += 12) {
uint256 id12x12 = LAYER_12x12 + x12i + y12i * GRID_SIZE;
require(_owners[id12x12] == 0, "Already minted as 12x12");
}
}
}
if (size <= 6) {
require(_owners[LAYER_6x6 + (x/6) * 6 + ((y/6) * 6) * GRID_SIZE] == 0, "Already minted as 6x6");
} else {
for (uint256 x6i = x; x6i < toX; x6i += 6) {
for (uint256 y6i = y; y6i < toY; y6i += 6) {
uint256 id6x6 = LAYER_6x6 + x6i + y6i * GRID_SIZE;
require(_owners[id6x6] == 0, "Already minted as 6x6");
}
}
}
if (size <= 3) {
require(_owners[LAYER_3x3 + (x/3) * 3 + ((y/3) * 3) * GRID_SIZE] == 0, "Already minted as 3x3");
} else {
for (uint256 x3i = x; x3i < toX; x3i += 3) {
for (uint256 y3i = y; y3i < toY; y3i += 3) {
uint256 id3x3 = LAYER_3x3 + x3i + y3i * GRID_SIZE;
require(_owners[id3x3] == 0, "Already minted as 3x3");
}
}
}
for (uint256 i = 0; i < size*size; i++) {
uint256 id = _idInPath(i, size, x, y);
require(_owners[id] == 0, "Already minted");
emit Transfer(address(0), to, id);
}
_owners[quadId] = uint256(to);
_numNFTPerAddress[to] += size * size;
_checkBatchReceiverAcceptQuad(msg.sender, address(0), to, size, x, y, data);
}
function _idInPath(uint256 i, uint256 size, uint256 x, uint256 y) internal pure returns(uint256) {
uint256 row = i / size;
if(row % 2 == 0) { // alow ids to follow a path in a quad
return (x + (i%size)) + ((y + row) * GRID_SIZE);
} else {
return ((x + size) - (1 + i%size)) + ((y + row) * GRID_SIZE);
}
}
/// @notice transfer one quad (aligned to a quad tree with size 3, 6, 12 or 24 only)
/// @param from current owner of the quad
/// @param to destination
/// @param size size of the quad
/// @param x The top left x coordinate of the quad
/// @param y The top left y coordinate of the quad
/// @param data additional data
function transferQuad(address from, address to, uint256 size, uint256 x, uint256 y, bytes calldata data) external {
require(from != address(0), "from is zero address");
require(to != address(0), "can't send to zero address");
bool metaTx = msg.sender != from && _metaTransactionContracts[msg.sender];
if (msg.sender != from && !metaTx) {
require(
_superOperators[msg.sender] ||
_operatorsForAll[from][msg.sender],
"not authorized to transferQuad"
);
}
_transferQuad(from, to, size, x, y);
_numNFTPerAddress[from] -= size * size;
_numNFTPerAddress[to] += size * size;
_checkBatchReceiverAcceptQuad(metaTx ? from : msg.sender, from, to, size, x, y, data);
}
function _checkBatchReceiverAcceptQuad(
address operator,
address from,
address to,
uint256 size,
uint256 x,
uint256 y,
bytes memory data
) internal {
if (to.isContract() && _checkInterfaceWith10000Gas(to, ERC721_MANDATORY_RECEIVER)) {
uint256[] memory ids = new uint256[](size*size);
for (uint256 i = 0; i < size*size; i++) {
ids[i] = _idInPath(i, size, x, y);
}
require(
_checkOnERC721BatchReceived(operator, from, to, ids, data),
"erc721 batch transfer rejected by to"
);
}
}
/// @notice transfer multiple quad (aligned to a quad tree with size 3, 6, 12 or 24 only)
/// @param from current owner of the quad
/// @param to destination
/// @param sizes list of sizes for each quad
/// @param xs list of top left x coordinates for each quad
/// @param ys list of top left y coordinates for each quad
/// @param data additional data
function batchTransferQuad(
address from,
address to,
uint256[] calldata sizes,
uint256[] calldata xs,
uint256[] calldata ys,
bytes calldata data
) external {
require(from != address(0), "from is zero address");
require(to != address(0), "can't send to zero address");
require(sizes.length == xs.length && xs.length == ys.length, "invalid data");
bool metaTx = msg.sender != from && _metaTransactionContracts[msg.sender];
if (msg.sender != from && !metaTx) {
require(
_superOperators[msg.sender] ||
_operatorsForAll[from][msg.sender],
"not authorized to transferMultiQuads"
);
}
uint256 numTokensTransfered = 0;
for (uint256 i = 0; i < sizes.length; i++) {
uint256 size = sizes[i];
_transferQuad(from, to, size, xs[i], ys[i]);
numTokensTransfered += size * size;
}
_numNFTPerAddress[from] -= numTokensTransfered;
_numNFTPerAddress[to] += numTokensTransfered;
if (to.isContract() && _checkInterfaceWith10000Gas(to, ERC721_MANDATORY_RECEIVER)) {
uint256[] memory ids = new uint256[](numTokensTransfered);
uint256 counter = 0;
for (uint256 j = 0; j < sizes.length; j++) {
uint256 size = sizes[j];
for (uint256 i = 0; i < size*size; i++) {
ids[counter] = _idInPath(i, size, xs[j], ys[j]);
counter++;
}
}
require(
_checkOnERC721BatchReceived(metaTx ? from : msg.sender, from, to, ids, data),
"erc721 batch transfer rejected by to"
);
}
}
function _transferQuad(address from, address to, uint256 size, uint256 x, uint256 y) internal {
if (size == 1) {
uint256 id1x1 = x + y * GRID_SIZE;
address owner = _ownerOf(id1x1);
require(owner != address(0), "token does not exist");
require(owner == from, "not owner in _transferQuad");
_owners[id1x1] = uint256(to);
} else {
_regroup(from, to, size, x, y);
}
for (uint256 i = 0; i < size*size; i++) {
emit Transfer(from, to, _idInPath(i, size, x, y));
}
}
function _checkAndClear(address from, uint256 id) internal returns(bool) {
uint256 owner = _owners[id];
if (owner != 0) {
require(address(owner) == from, "not owner");
_owners[id] = 0;
return true;
}
return false;
}
function _regroup(address from, address to, uint256 size, uint256 x, uint256 y) internal {
require(x % size == 0 && y % size == 0, "Invalid coordinates");
require(x <= GRID_SIZE - size && y <= GRID_SIZE - size, "Out of bounds");
if (size == 3) {
_regroup3x3(from, to, x, y, true);
} else if (size == 6) {
_regroup6x6(from, to, x, y, true);
} else if (size == 12) {
_regroup12x12(from, to, x, y, true);
} else if (size == 24) {
_regroup24x24(from, to, x, y, true);
} else {
require(false, "Invalid size");
}
}
function _regroup3x3(address from, address to, uint256 x, uint256 y, bool set) internal returns (bool) {
uint256 id = x + y * GRID_SIZE;
uint256 quadId = LAYER_3x3 + id;
bool ownerOfAll = true;
for (uint256 xi = x; xi < x+3; xi++) {
for (uint256 yi = y; yi < y+3; yi++) {
ownerOfAll = _checkAndClear(from, xi + yi * GRID_SIZE) && ownerOfAll;
}
}
if(set) {
if(!ownerOfAll) {
require(
_owners[quadId] == uint256(from) ||
_owners[LAYER_6x6 + (x/6) * 6 + ((y/6) * 6) * GRID_SIZE] == uint256(from) ||
_owners[LAYER_12x12 + (x/12) * 12 + ((y/12) * 12) * GRID_SIZE] == uint256(from) ||
_owners[LAYER_24x24 + (x/24) * 24 + ((y/24) * 24) * GRID_SIZE] == uint256(from),
"not owner of all sub quads nor parent quads"
);
}
_owners[quadId] = uint256(to);
return true;
}
return ownerOfAll;
}
function _regroup6x6(address from, address to, uint256 x, uint256 y, bool set) internal returns (bool) {
uint256 id = x + y * GRID_SIZE;
uint256 quadId = LAYER_6x6 + id;
bool ownerOfAll = true;
for (uint256 xi = x; xi < x+6; xi += 3) {
for (uint256 yi = y; yi < y+6; yi += 3) {
bool ownAllIndividual = _regroup3x3(from, to, xi, yi, false);
uint256 id3x3 = LAYER_3x3 + xi + yi * GRID_SIZE;
uint256 owner3x3 = _owners[id3x3];
if (owner3x3 != 0) {
if(!ownAllIndividual) {
require(owner3x3 == uint256(from), "not owner of 3x3 quad");
}
_owners[id3x3] = 0;
}
ownerOfAll = (ownAllIndividual || owner3x3 != 0) && ownerOfAll;
}
}
if(set) {
if(!ownerOfAll) {
require(
_owners[quadId] == uint256(from) ||
_owners[LAYER_12x12 + (x/12) * 12 + ((y/12) * 12) * GRID_SIZE] == uint256(from) ||
_owners[LAYER_24x24 + (x/24) * 24 + ((y/24) * 24) * GRID_SIZE] == uint256(from),
"not owner of all sub quads nor parent quads"
);
}
_owners[quadId] = uint256(to);
return true;
}
return ownerOfAll;
}
function _regroup12x12(address from, address to, uint256 x, uint256 y, bool set) internal returns (bool) {
uint256 id = x + y * GRID_SIZE;
uint256 quadId = LAYER_12x12 + id;
bool ownerOfAll = true;
for (uint256 xi = x; xi < x+12; xi += 6) {
for (uint256 yi = y; yi < y+12; yi += 6) {
bool ownAllIndividual = _regroup6x6(from, to, xi, yi, false);
uint256 id6x6 = LAYER_6x6 + xi + yi * GRID_SIZE;
uint256 owner6x6 = _owners[id6x6];
if (owner6x6 != 0) {
if(!ownAllIndividual) {
require(owner6x6 == uint256(from), "not owner of 6x6 quad");
}
_owners[id6x6] = 0;
}
ownerOfAll = (ownAllIndividual || owner6x6 != 0) && ownerOfAll;
}
}
if(set) {
if(!ownerOfAll) {
require(
_owners[quadId] == uint256(from) ||
_owners[LAYER_24x24 + (x/24) * 24 + ((y/24) * 24) * GRID_SIZE] == uint256(from),
"not owner of all sub quads nor parent quads"
);
}
_owners[quadId] = uint256(to);
return true;
}
return ownerOfAll;
}
function _regroup24x24(address from, address to, uint256 x, uint256 y, bool set) internal returns (bool) {
uint256 id = x + y * GRID_SIZE;
uint256 quadId = LAYER_24x24 + id;
bool ownerOfAll = true;
for (uint256 xi = x; xi < x+24; xi += 12) {
for (uint256 yi = y; yi < y+24; yi += 12) {
bool ownAllIndividual = _regroup12x12(from, to, xi, yi, false);
uint256 id12x12 = LAYER_12x12 + xi + yi * GRID_SIZE;
uint256 owner12x12 = _owners[id12x12];
if (owner12x12 != 0) {
if(!ownAllIndividual) {
require(owner12x12 == uint256(from), "not owner of 12x12 quad");
}
_owners[id12x12] = 0;
}
ownerOfAll = (ownAllIndividual || owner12x12 != 0) && ownerOfAll;
}
}
if(set) {
if(!ownerOfAll) {
require(
_owners[quadId] == uint256(from),
"not owner of all sub quads not parent quad"
);
}
_owners[quadId] = uint256(to);
return true;
}
return ownerOfAll || _owners[quadId] == uint256(from);
}
function _ownerOf(uint256 id) internal view returns (address) {
require(id & LAYER == 0, "Invalid token id");
uint256 x = id % GRID_SIZE;
uint256 y = id / GRID_SIZE;
uint256 owner1x1 = _owners[id];
if (owner1x1 != 0) {
return address(owner1x1); // cast to zero
} else {
address owner3x3 = address(_owners[LAYER_3x3 + (x/3) * 3 + ((y/3) * 3) * GRID_SIZE]);
if (owner3x3 != address(0)) {
return owner3x3;
} else {
address owner6x6 = address(_owners[LAYER_6x6 + (x/6) * 6 + ((y/6) * 6) * GRID_SIZE]);
if (owner6x6 != address(0)) {
return owner6x6;
} else {
address owner12x12 = address(_owners[LAYER_12x12 + (x/12) * 12 + ((y/12) * 12) * GRID_SIZE]);
if (owner12x12 != address(0)) {
return owner12x12;
} else {
return address(_owners[LAYER_24x24 + (x/24) * 24 + ((y/24) * 24) * GRID_SIZE]);
}
}
}
}
}
function _ownerAndOperatorEnabledOf(uint256 id) internal view returns (address owner, bool operatorEnabled) {
require(id & LAYER == 0, "Invalid token id");
uint256 x = id % GRID_SIZE;
uint256 y = id / GRID_SIZE;
uint256 owner1x1 = _owners[id];
if (owner1x1 != 0) {
owner = address(owner1x1);
operatorEnabled = (owner1x1 / 2**255) == 1;
} else {
address owner3x3 = address(_owners[LAYER_3x3 + (x/3) * 3 + ((y/3) * 3) * GRID_SIZE]);
if (owner3x3 != address(0)) {
owner = owner3x3;
operatorEnabled = false;
} else {
address owner6x6 = address(_owners[LAYER_6x6 + (x/6) * 6 + ((y/6) * 6) * GRID_SIZE]);
if (owner6x6 != address(0)) {
owner = owner6x6;
operatorEnabled = false;
} else {
address owner12x12 = address(_owners[LAYER_12x12 + (x/12) * 12 + ((y/12) * 12) * GRID_SIZE]);
if (owner12x12 != address(0)) {
owner = owner12x12;
operatorEnabled = false;
} else {
owner = address(_owners[LAYER_24x24 + (x/24) * 24 + ((y/24) * 24) * GRID_SIZE]);
operatorEnabled = false;
}
}
}
}
}
}
pragma solidity ^0.5.2;
/**
Note: The ERC-165 identifier for this interface is 0x5e8bf644.
*/
interface ERC721MandatoryTokenReceiver {
function onERC721BatchReceived(
address operator,
address from,
uint256[] calldata ids,
bytes calldata data
) external returns (bytes4); // needs to return 0x4b808c46
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4); // needs to return 0x150b7a02
// needs to implements EIP-165
// function supportsInterface(bytes4 interfaceId)
// external
// view
// returns (bool);
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity 0.5.9;
/// @dev minimal ERC2771 handler to keep bytecode-size down.
/// based on: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/metatx/ERC2771Context.sol
contract ERC2771Handler {
address internal _trustedForwarder;
function __ERC2771Handler_initialize(address forwarder) internal {
_trustedForwarder = forwarder;
}
function isTrustedForwarder(address forwarder) public view returns (bool) {
return forwarder == _trustedForwarder;
}
function getTrustedForwarder() external view returns (address trustedForwarder) {
return _trustedForwarder;
}
function _msgSender() internal view returns (address sender) {
if (isTrustedForwarder(msg.sender)) {
// The assembly code is more direct than the Solidity version using `abi.decode`.
// solhint-disable-next-line no-inline-assembly
assembly {
sender := shr(96, calldataload(sub(calldatasize(), 20)))
}
} else {
return msg.sender;
}
}
}
pragma solidity ^0.5.2;
import "./Admin.sol";
/**
* @title PausableWithAdmin
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract PausableWithAdmin is Admin {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the admin to pause, triggers stopped state
*/
function pause() public onlyAdmin whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the admin to unpause, returns to normal state
*/
function unpause() public onlyAdmin whenPaused {
paused = false;
emit Unpause();
}
}
/* solhint-disable func-order, code-complexity */
pragma solidity 0.5.9;
import "../../contracts_common/Libraries/AddressUtils.sol";
import "../../contracts_common/Interfaces/ERC721TokenReceiver.sol";
import "../../contracts_common/Interfaces/ERC721Events.sol";
import "../../contracts_common/BaseWithStorage/SuperOperators.sol";
import "../../contracts_common/BaseWithStorage/MetaTransactionReceiver.sol";
import "../../contracts_common/Interfaces/ERC721MandatoryTokenReceiver.sol";
contract ERC721BaseToken is ERC721Events, SuperOperators, MetaTransactionReceiver {
using AddressUtils for address;
bytes4 internal constant _ERC721_RECEIVED = 0x150b7a02;
bytes4 internal constant _ERC721_BATCH_RECEIVED = 0x4b808c46;
bytes4 internal constant ERC165ID = 0x01ffc9a7;
bytes4 internal constant ERC721_MANDATORY_RECEIVER = 0x5e8bf644;
mapping (address => uint256) public _numNFTPerAddress;
mapping (uint256 => uint256) public _owners;
mapping (address => mapping(address => bool)) public _operatorsForAll;
mapping (uint256 => address) public _operators;
bool internal _initialized;
modifier initializer() {
require(!_initialized, "ERC721BaseToken: Contract already initialized");
_;
}
function initialize (
address metaTransactionContract,
address admin
) public initializer {
_admin = admin;
_setMetaTransactionProcessor(metaTransactionContract, true);
_initialized = true;
}
function _transferFrom(address from, address to, uint256 id) internal {
_numNFTPerAddress[from]--;
_numNFTPerAddress[to]++;
_owners[id] = uint256(to);
emit Transfer(from, to, id);
}
/**
* @notice Return the number of Land owned by an address
* @param owner The address to look for
* @return The number of Land token owned by the address
*/
function balanceOf(address owner) external view returns (uint256) {
require(owner != address(0), "owner is zero address");
return _numNFTPerAddress[owner];
}
function _ownerOf(uint256 id) internal view returns (address) {
return address(_owners[id]);
}
function _ownerAndOperatorEnabledOf(uint256 id) internal view returns (address owner, bool operatorEnabled) {
uint256 data = _owners[id];
owner = address(data);
operatorEnabled = (data / 2**255) == 1;
}
/**
* @notice Return the owner of a Land
* @param id The id of the Land
* @return The address of the owner
*/
function ownerOf(uint256 id) external view returns (address owner) {
owner = _ownerOf(id);
require(owner != address(0), "token does not exist");
}
function _approveFor(address owner, address operator, uint256 id) internal {
if(operator == address(0)) {
_owners[id] = uint256(owner); // no need to resset the operator, it will be overriden next time
} else {
_owners[id] = uint256(owner) + 2**255;
_operators[id] = operator;
}
emit Approval(owner, operator, id);
}
/**
* @notice Approve an operator to spend tokens on the sender behalf
* @param sender The address giving the approval
* @param operator The address receiving the approval
* @param id The id of the token
*/
function approveFor(
address sender,
address operator,
uint256 id
) external {
address owner = _ownerOf(id);
require(sender != address(0), "sender is zero address");
require(
msg.sender == sender ||
_metaTransactionContracts[msg.sender] ||
_superOperators[msg.sender] ||
_operatorsForAll[sender][msg.sender],
"not authorized to approve"
);
require(owner == sender, "owner != sender");
_approveFor(owner, operator, id);
}
/**
* @notice Approve an operator to spend tokens on the sender behalf
* @param operator The address receiving the approval
* @param id The id of the token
*/
function approve(address operator, uint256 id) external {
address owner = _ownerOf(id);
require(owner != address(0), "token does not exist");
require(
owner == msg.sender ||
_superOperators[msg.sender] ||
_operatorsForAll[owner][msg.sender],
"not authorized to approve"
);
_approveFor(owner, operator, id);
}
/**
* @notice Get the approved operator for a specific token
* @param id The id of the token
* @return The address of the operator
*/
function getApproved(uint256 id) external view returns (address) {
(address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id);
require(owner != address(0), "token does not exist");
if (operatorEnabled) {
return _operators[id];
} else {
return address(0);
}
}
function _checkTransfer(address from, address to, uint256 id) internal view returns (bool isMetaTx) {
(address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id);
require(owner != address(0), "token does not exist");
require(owner == from, "not owner in _checkTransfer");
require(to != address(0), "can't send to zero address");
isMetaTx = msg.sender != from && _metaTransactionContracts[msg.sender];
if (msg.sender != from && !isMetaTx) {
require(
_superOperators[msg.sender] ||
_operatorsForAll[from][msg.sender] ||
(operatorEnabled && _operators[id] == msg.sender),
"not approved to transfer"
);
}
}
function _checkInterfaceWith10000Gas(address _contract, bytes4 interfaceId)
internal
view
returns (bool)
{
bool success;
bool result;
bytes memory call_data = abi.encodeWithSelector(
ERC165ID,
interfaceId
);
// solium-disable-next-line security/no-inline-assembly
assembly {
let call_ptr := add(0x20, call_data)
let call_size := mload(call_data)
let output := mload(0x40) // Find empty storage location using "free memory pointer"
mstore(output, 0x0)
success := staticcall(
10000,
_contract,
call_ptr,
call_size,
output,
0x20
) // 32 bytes
result := mload(output)
}
// (10000 / 63) "not enough for supportsInterface(...)" // consume all gas, so caller can potentially know that there was not enough gas
assert(gasleft() > 158);
return success && result;
}
/**
* @notice Transfer a token between 2 addresses
* @param from The sender of the token
* @param to The recipient of the token
* @param id The id of the token
*/
function transferFrom(address from, address to, uint256 id) external {
bool metaTx = _checkTransfer(from, to, id);
_transferFrom(from, to, id);
if (to.isContract() && _checkInterfaceWith10000Gas(to, ERC721_MANDATORY_RECEIVER)) {
require(
_checkOnERC721Received(metaTx ? from : msg.sender, from, to, id, ""),
"erc721 transfer rejected by to"
);
}
}
/**
* @notice Transfer a token between 2 addresses letting the receiver knows of the transfer
* @param from The sender of the token
* @param to The recipient of the token
* @param id The id of the token
* @param data Additional data
*/
function safeTransferFrom(address from, address to, uint256 id, bytes memory data) public {
bool metaTx = _checkTransfer(from, to, id);
_transferFrom(from, to, id);
if (to.isContract()) {
require(
_checkOnERC721Received(metaTx ? from : msg.sender, from, to, id, data),
"ERC721: transfer rejected by to"
);
}
}
/**
* @notice Transfer a token between 2 addresses letting the receiver knows of the transfer
* @param from The send of the token
* @param to The recipient of the token
* @param id The id of the token
*/
function safeTransferFrom(address from, address to, uint256 id) external {
safeTransferFrom(from, to, id, "");
}
/**
* @notice Transfer many tokens between 2 addresses
* @param from The sender of the token
* @param to The recipient of the token
* @param ids The ids of the tokens
* @param data additional data
*/
function batchTransferFrom(address from, address to, uint256[] calldata ids, bytes calldata data) external {
_batchTransferFrom(from, to, ids, data, false);
}
function _batchTransferFrom(address from, address to, uint256[] memory ids, bytes memory data, bool safe) internal {
bool metaTx = msg.sender != from && _metaTransactionContracts[msg.sender];
bool authorized = msg.sender == from ||
metaTx ||
_superOperators[msg.sender] ||
_operatorsForAll[from][msg.sender];
require(from != address(0), "from is zero address");
require(to != address(0), "can't send to zero address");
uint256 numTokens = ids.length;
for(uint256 i = 0; i < numTokens; i ++) {
uint256 id = ids[i];
(address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id);
require(owner == from, "not owner in batchTransferFrom");
require(authorized || (operatorEnabled && _operators[id] == msg.sender), "not authorized");
_owners[id] = uint256(to);
emit Transfer(from, to, id);
}
if (from != to) {
_numNFTPerAddress[from] -= numTokens;
_numNFTPerAddress[to] += numTokens;
}
if (to.isContract() && (safe || _checkInterfaceWith10000Gas(to, ERC721_MANDATORY_RECEIVER))) {
require(
_checkOnERC721BatchReceived(metaTx ? from : msg.sender, from, to, ids, data),
"erc721 batch transfer rejected by to"
);
}
}
/**
* @notice Transfer many tokens between 2 addresses ensuring the receiving contract has a receiver method
* @param from The sender of the token
* @param to The recipient of the token
* @param ids The ids of the tokens
* @param data additional data
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, bytes calldata data) external {
_batchTransferFrom(from, to, ids, data, true);
}
/**
* @notice Check if the contract supports an interface
* 0x01ffc9a7 is ERC-165
* 0x80ac58cd is ERC-721
* @param id The id of the interface
* @return True if the interface is supported
*/
function supportsInterface(bytes4 id) external pure returns (bool) {
return id == 0x01ffc9a7 || id == 0x80ac58cd;
}
/**
* @notice Set the approval for an operator to manage all the tokens of the sender
* @param sender The address giving the approval
* @param operator The address receiving the approval
* @param approved The determination of the approval
*/
function setApprovalForAllFor(
address sender,
address operator,
bool approved
) external {
require(sender != address(0), "Invalid sender address");
require(
msg.sender == sender ||
_metaTransactionContracts[msg.sender] ||
_superOperators[msg.sender],
"not authorized to approve for all"
);
_setApprovalForAll(sender, operator, approved);
}
/**
* @notice Set the approval for an operator to manage all the tokens of the sender
* @param operator The address receiving the approval
* @param approved The determination of the approval
*/
function setApprovalForAll(address operator, bool approved) external {
_setApprovalForAll(msg.sender, operator, approved);
}
function _setApprovalForAll(
address sender,
address operator,
bool approved
) internal {
require(
!_superOperators[operator],
"super operator can't have their approvalForAll changed"
);
_operatorsForAll[sender][operator] = approved;
emit ApprovalForAll(sender, operator, approved);
}
/**
* @notice Check if the sender approved the operator
* @param owner The address of the owner
* @param operator The address of the operator
* @return The status of the approval
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool isOperator)
{
return _operatorsForAll[owner][operator] || _superOperators[operator];
}
function _burn(address from, address owner, uint256 id) internal {
require(from == owner, "not owner");
_owners[id] = 2**160; // cannot mint it again
_numNFTPerAddress[from]--;
emit Transfer(from, address(0), id);
}
/// @notice Burns token `id`.
/// @param id token which will be burnt.
function burn(uint256 id) external {
_burn(msg.sender, _ownerOf(id), id);
}
/// @notice Burn token`id` from `from`.
/// @param from address whose token is to be burnt.
/// @param id token which will be burnt.
function burnFrom(address from, uint256 id) external {
require(from != address(0), "Invalid sender address");
(address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id);
require(
msg.sender == from ||
_metaTransactionContracts[msg.sender] ||
(operatorEnabled && _operators[id] == msg.sender) ||
_superOperators[msg.sender] ||
_operatorsForAll[from][msg.sender],
"not authorized to burn"
);
_burn(from, owner, id);
}
function _checkOnERC721Received(address operator, address from, address to, uint256 tokenId, bytes memory _data)
internal returns (bool)
{
bytes4 retval = ERC721TokenReceiver(to).onERC721Received(operator, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
function _checkOnERC721BatchReceived(address operator, address from, address to, uint256[] memory ids, bytes memory _data)
internal returns (bool)
{
bytes4 retval = ERC721MandatoryTokenReceiver(to).onERC721BatchReceived(operator, from, ids, _data);
return (retval == _ERC721_BATCH_RECEIVED);
}
// Empty storage space in contracts for future enhancements
// ref: https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/issues/13)
uint256[49] private __gap;
}
pragma solidity ^0.5.2;
library AddressUtils {
function toPayable(address _address) internal pure returns (address payable _payable) {
return address(uint160(_address));
}
function isContract(address addr) internal view returns (bool) {
// for accounts without code, i.e. `keccak256('')`:
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
bytes32 codehash;
// solium-disable-next-line security/no-inline-assembly
assembly {
codehash := extcodehash(addr)
}
return (codehash != 0x0 && codehash != accountHash);
}
}
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This code has not been reviewed.
* Do not use or deploy this code before reviewing it personally first.
*/
// solhint-disable-next-line compiler-fixed
pragma solidity ^0.5.2;
interface ERC721TokenReceiver {
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
pragma solidity ^0.5.2;
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
interface ERC721Events {
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
}
pragma solidity ^0.5.2;
import "./Admin.sol";
contract SuperOperators is Admin {
mapping(address => bool) internal _superOperators;
event SuperOperator(address superOperator, bool enabled);
/// @notice Enable or disable the ability of `superOperator` to transfer tokens of all (superOperator rights).
/// @param superOperator address that will be given/removed superOperator right.
/// @param enabled set whether the superOperator is enabled or disabled.
function setSuperOperator(address superOperator, bool enabled) external {
require(
msg.sender == _admin,
"only admin is allowed to add super operators"
);
_superOperators[superOperator] = enabled;
emit SuperOperator(superOperator, enabled);
}
/// @notice check whether address `who` is given superOperator rights.
/// @param who The address to query.
/// @return whether the address has superOperator rights.
function isSuperOperator(address who) public view returns (bool) {
return _superOperators[who];
}
}
pragma solidity ^0.5.2;
import "./Admin.sol";
contract MetaTransactionReceiver is Admin{
mapping(address => bool) internal _metaTransactionContracts;
event MetaTransactionProcessor(address metaTransactionProcessor, bool enabled);
/// @notice Enable or disable the ability of `metaTransactionProcessor` to perform meta-tx (metaTransactionProcessor rights).
/// @param metaTransactionProcessor address that will be given/removed metaTransactionProcessor rights.
/// @param enabled set whether the metaTransactionProcessor is enabled or disabled.
function setMetaTransactionProcessor(address metaTransactionProcessor, bool enabled) public {
require(
msg.sender == _admin,
"only admin can setup metaTransactionProcessors"
);
_setMetaTransactionProcessor(metaTransactionProcessor, enabled);
}
function _setMetaTransactionProcessor(address metaTransactionProcessor, bool enabled) internal {
_metaTransactionContracts[metaTransactionProcessor] = enabled;
emit MetaTransactionProcessor(metaTransactionProcessor, enabled);
}
/// @notice check whether address `who` is given meta-transaction execution rights.
/// @param who The address to query.
/// @return whether the address has meta-transaction execution rights.
function isMetaTransactionProcessor(address who) external view returns(bool) {
return _metaTransactionContracts[who];
}
}
pragma solidity ^0.5.2;
contract Admin {
address internal _admin;
event AdminChanged(address oldAdmin, address newAdmin);
/// @notice gives the current administrator of this contract.
/// @return the current administrator of this contract.
function getAdmin() external view returns (address) {
return _admin;
}
/// @notice change the administrator to be `newAdmin`.
/// @param newAdmin address of the new administrator.
function changeAdmin(address newAdmin) external {
require(msg.sender == _admin, "only admin can change admin");
emit AdminChanged(_admin, newAdmin);
_admin = newAdmin;
}
modifier onlyAdmin() {
require (msg.sender == _admin, "only admin allowed");
_;
}
} | @notice transfer multiple quad (aligned to a quad tree with size 3, 6, 12 or 24 only) @param from current owner of the quad @param to destination @param sizes list of sizes for each quad @param xs list of top left x coordinates for each quad @param ys list of top left y coordinates for each quad @param data additional data | ) external {
require(from != address(0), "from is zero address");
require(to != address(0), "can't send to zero address");
require(sizes.length == xs.length && xs.length == ys.length, "invalid data");
bool metaTx = msg.sender != from && _metaTransactionContracts[msg.sender];
function batchTransferQuad(
address from,
address to,
uint256[] calldata sizes,
uint256[] calldata xs,
uint256[] calldata ys,
bytes calldata data
if (msg.sender != from && !metaTx) {
require(
_superOperators[msg.sender] ||
_operatorsForAll[from][msg.sender],
"not authorized to transferMultiQuads"
);
}
uint256 numTokensTransfered = 0;
for (uint256 i = 0; i < sizes.length; i++) {
uint256 size = sizes[i];
_transferQuad(from, to, size, xs[i], ys[i]);
numTokensTransfered += size * size;
}
_numNFTPerAddress[from] -= numTokensTransfered;
_numNFTPerAddress[to] += numTokensTransfered;
if (to.isContract() && _checkInterfaceWith10000Gas(to, ERC721_MANDATORY_RECEIVER)) {
uint256[] memory ids = new uint256[](numTokensTransfered);
uint256 counter = 0;
for (uint256 j = 0; j < sizes.length; j++) {
uint256 size = sizes[j];
for (uint256 i = 0; i < size*size; i++) {
ids[counter] = _idInPath(i, size, xs[j], ys[j]);
counter++;
}
}
require(
_checkOnERC721BatchReceived(metaTx ? from : msg.sender, from, to, ids, data),
"erc721 batch transfer rejected by to"
);
}
if (to.isContract() && _checkInterfaceWith10000Gas(to, ERC721_MANDATORY_RECEIVER)) {
uint256[] memory ids = new uint256[](numTokensTransfered);
uint256 counter = 0;
for (uint256 j = 0; j < sizes.length; j++) {
uint256 size = sizes[j];
for (uint256 i = 0; i < size*size; i++) {
ids[counter] = _idInPath(i, size, xs[j], ys[j]);
counter++;
}
}
require(
_checkOnERC721BatchReceived(metaTx ? from : msg.sender, from, to, ids, data),
"erc721 batch transfer rejected by to"
);
}
if (to.isContract() && _checkInterfaceWith10000Gas(to, ERC721_MANDATORY_RECEIVER)) {
uint256[] memory ids = new uint256[](numTokensTransfered);
uint256 counter = 0;
for (uint256 j = 0; j < sizes.length; j++) {
uint256 size = sizes[j];
for (uint256 i = 0; i < size*size; i++) {
ids[counter] = _idInPath(i, size, xs[j], ys[j]);
counter++;
}
}
require(
_checkOnERC721BatchReceived(metaTx ? from : msg.sender, from, to, ids, data),
"erc721 batch transfer rejected by to"
);
}
}
| 1,471,374 | [
1,
13866,
3229,
9474,
261,
20677,
358,
279,
9474,
2151,
598,
963,
890,
16,
1666,
16,
2593,
578,
4248,
1338,
13,
225,
628,
783,
3410,
434,
326,
9474,
225,
358,
2929,
225,
8453,
666,
434,
8453,
364,
1517,
9474,
225,
9280,
666,
434,
1760,
2002,
619,
5513,
364,
1517,
9474,
225,
16036,
666,
434,
1760,
2002,
677,
5513,
364,
1517,
9474,
225,
501,
3312,
501,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
262,
3903,
288,
203,
3639,
2583,
12,
2080,
480,
1758,
12,
20,
3631,
315,
2080,
353,
3634,
1758,
8863,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
4169,
1404,
1366,
358,
3634,
1758,
8863,
203,
3639,
2583,
12,
11914,
18,
2469,
422,
9280,
18,
2469,
597,
9280,
18,
2469,
422,
16036,
18,
2469,
16,
315,
5387,
501,
8863,
203,
3639,
1426,
2191,
4188,
273,
1234,
18,
15330,
480,
628,
597,
389,
3901,
3342,
20723,
63,
3576,
18,
15330,
15533,
203,
565,
445,
2581,
5912,
24483,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
8453,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
9280,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
16036,
16,
203,
3639,
1731,
745,
892,
501,
203,
3639,
309,
261,
3576,
18,
15330,
480,
628,
597,
401,
3901,
4188,
13,
288,
203,
5411,
2583,
12,
203,
7734,
389,
9565,
24473,
63,
3576,
18,
15330,
65,
747,
203,
7734,
389,
30659,
1290,
1595,
63,
2080,
6362,
3576,
18,
15330,
6487,
203,
7734,
315,
902,
10799,
358,
7412,
5002,
928,
17318,
6,
203,
5411,
11272,
203,
3639,
289,
203,
3639,
2254,
5034,
818,
5157,
5912,
329,
273,
374,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
8453,
18,
2469,
31,
277,
27245,
288,
203,
5411,
2254,
5034,
963,
273,
8453,
63,
77,
15533,
203,
5411,
389,
13866,
24483,
12,
2080,
16,
358,
16,
963,
16,
9280,
63,
77,
6487,
16036,
63,
77,
19226,
203,
2
]
|
//COPYRIGHT © THE FORCE PROTOCOL FOUNDATION LTD.
//原力协议稳定币系统 - 清算拍卖
pragma solidity >= 0.5.0;
contract IAsset {
function move(address from, address to, uint256 amt) public;
}
contract IWallet {
function get(address tok) public returns(address);
}
contract Liquidauction {
struct state {
uint256 bid; //当前出价
address win; //当前最高出价者
uint32 ttl; //当前出价的过期时间
uint32 exp; //本次拍卖结束时间
address who; //拍卖品所属账户, 接收卖出的资产退回();
uint256 rem; //未卖出的抵押物数量(remainder);
address rve; //接收拍卖收益的账户(received)
uint256 oam; //被拍卖的资产数量(out amount)
uint256 iam; //预期收益资产数量(int amount)
address oss; //被拍卖的资产地址(out address)
address iss; //收益资产地址(in address)
}
event End(uint256 id);
event Auction(uint256 id, address who, address rve, address oss,
uint256 oam, address iss, uint256 iam, uint256 bid);
mapping (uint256 => state) public states;
IWallet public wet; //wallet
constructor(address w) public {
wet = IWallet(w);
}
/** 拍卖参数 */
uint256 public inc = 1.05E18; //最小竞拍加价 (5%)
uint32 public ttl = 2 hours; //单次竞价有效时间.
uint32 public exp = 1 days; //整个拍卖持续时间.
uint256 public nonce = 0; //拍卖 id
//发起拍卖
//@who 拍卖品所属账户, 接收卖出的资产退回
//@rve 接收拍卖收益的账户(received)
//@oam 被拍卖的资产数量(out amount)
//@iam 预期收益资产数量(in amount)
//@bid 起拍价
//@oss 被拍卖的资产地址
//@iss 收益资产地址(QIAN)
function auction(address who, address rve, address oss,
uint256 oam, address iss, uint256 iam, uint256 bid)
public returns(uint256) {
uint256 id = nonce++;
states[id].bid = bid;
states[id].win = rve;
states[id].exp = uint32(now) + exp;
states[id].ttl = 0;
states[id].who = who;
states[id].rve = rve;
states[id].rem = oam;
states[id].oam = oam;
states[id].oss = oss;
states[id].iam = iam;
states[id].iss = iss;
emit Auction(id, who, rve, oss, oam, iss, iam, bid);
}
//拍卖第一阶段, 固定抵押物数量, 直到出价高于预期要拍卖的稳定币数量 @auction.iam 后转为第二阶段竞拍.
function upward(uint id, uint oam, uint bid) public {
state memory a = states[id];
//检查当前出价者是否有效
require(a.win != address(0), "require: invalid address a.win");
//检测当前叫价是否过期
require(a.ttl > now || a.ttl == 0, "require: bid has expired");
//检测拍卖是否结束
require(a.exp > now, "require: auction has ended");
//固定拍卖物数量的前提下增高叫价 @bid.
require(oam == a.oam, "require: oam == a.oam");
//第一阶段最高出价只能到预期要拍卖的资产数量, 也就是说拍卖出价上限为 a.iam.
require(bid <= a.iam, "require: bid < a.iam");
//最新的出价只能比之前的价格更高.
require(bid > a.bid, "require: bid > a.bid");
//每次出价必须比上一次的出价高出 @inc, 或者出价已经是最大(等于 @a.iam)
require(bid >= umul(inc, a.bid) || bid == a.iam, "require: bid >= umul(inc, a.bid) || bid == a.iam");
//从钱包中读取资产对象.
IAsset bet = IAsset(wet.get(a.iss));
//将竞拍者的出价转给当前合约.
bet.move(msg.sender, address(this), bid);
//将上一次竞拍者 @a.win 的出价资产归还
bet.move(address(this), a.win, a.bid);
//更新本次出价者为最高出价者, 本次出价为最高出价, 本次出价过期时间.
states[id].win = msg.sender;
states[id].bid = bid;
states[id].ttl = uint32(now) + ttl;
}
//拍卖第二阶段, 固定价格, 竞拍者通过降低拍卖物数量来参与竞拍, 数量最低者将成交.
function downward(uint id, uint oam, uint bid) public {
state memory a = states[id];
require(a.win != address(0), "require: invalid address a.win");
require(a.ttl > now || a.ttl == 0, "require: bid has expired");
require(a.exp > now, "require: auction has ended");
//固定出价的前提下减少抵押物的数量 @oam
require(bid == a.bid);
require(bid == a.iam);
require(oam < a.oam);
//竞拍减少的抵押物数量必须满足 @inc 配置的步长.
require(umul(inc, oam) <= a.oam);
//将上一次的竞拍者 @a.win 的出价资产归还
IAsset(wet.get(a.iss)).move(msg.sender, a.win, bid);
//更新最新的最高出价者, 拍卖品数量, 本次出价的过期时间.
states[id].win = msg.sender;
states[id].oam = oam;
states[id].ttl = uint32(now) + ttl;
}
//结束拍卖, 仅当拍卖有至少一次竞拍时才允许调用.
function end(uint id) public {
state memory a = states[id];
//检测拍卖是否完成(并且有参与竞拍)
require(a.ttl != 0 && (a.ttl < now || a.exp < now), "auction is not end yet");
//派发拍卖品
IAsset(wet.get(a.oss)).move(address(this), a.win, a.oam);
//将剩余拍卖品转给原持有者(退回到钱包中)
IAsset(wet.get(a.oss)).move(address(this), a.who, usub(a.rem, a.oam));
//派发收益
IAsset(wet.get(a.iss)).move(address(this), a.rve, a.bid);
delete states[id];
emit End(id);
}
function usub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x >= y);
z = x - y;
}
function umul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x * y;
require(y == 0 || z / y == x);
z = z / PRE;
}
uint256 constant public PRE = 10 ** 18;
} | 被拍卖的资产数量(out amount)
| uint256 oam; | 12,982,863 | [
1,
169,
100,
109,
167,
238,
240,
166,
240,
249,
168,
253,
231,
169,
118,
231,
165,
123,
105,
167,
248,
113,
170,
234,
242,
12,
659,
3844,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
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,
3639,
2254,
5034,
320,
301,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
/**
* @title ScryptFramework
* @author Christian Reitwiessner
*/
abstract contract ScryptFramework {
// The state object, can be used in both generating and verifying mode.
// In generating mode, only vars and fullMemory is used, in verifying
// mode only vars and memoryHash is used.
struct State {
uint[4] vars;
bytes32 memoryHash;
// We need the input as part of the state because it is required
// for the final step.
bytes32 inputHash;
// This is not available in verification mode.
uint[] fullMemory;
}
// This is the witness data that is generated in generating mode
// and used for verification in verification mode.
struct Proofs {
bool generateProofs;
bool verificationError;
bytes32[] proof;
}
// Only used for testing.
/**
* @dev hashes a state struct instance
*
* @param state the state struct instance to hash
*
* @return returns the hash
*/
function hashState(State memory state) pure internal returns (bytes32) {
return keccak256(abi.encodePacked(state.memoryHash, state.vars, state.inputHash));
}
/**
* @dev serializes a State struct instance
*
* @param state the State struct instance to be serialized
*
* @return encodedState returns the serialized Struct instance
*/
function encodeState(State memory state) pure internal returns (bytes memory encodedState) {
encodedState = abi.encodePacked(
state.vars[0],
state.vars[1],
state.vars[2],
state.vars[3],
state.memoryHash,
state.inputHash
);
}
/**
* @dev de-serializes a State struct instance
*
* @param encoded the serialized State struct instance
*
* @return error is true if the input size is wrong
* @return state State struct instance
*/
function decodeState(bytes memory encoded) pure internal returns (bool error, State memory state) {
if (encoded.length != 0x20 * 4 + 0x20 + 0x20) {
return (true, state);
}
uint[4] memory vars = state.vars;
bytes32 memoryHash;
bytes32 inputHash;
assembly {
mstore(add(vars, 0x00), mload(add(encoded, 0x20)))
mstore(add(vars, 0x20), mload(add(encoded, 0x40)))
mstore(add(vars, 0x40), mload(add(encoded, 0x60)))
mstore(add(vars, 0x60), mload(add(encoded, 0x80)))
memoryHash := mload(add(encoded, 0xa0))
inputHash := mload(add(encoded, 0xc0))
}
state.memoryHash = memoryHash;
state.inputHash = inputHash;
return (false, state);
}
/**
* @dev checks for equality of a and b's hash
*
* @param a the first equality operand
* @param b the second equality operand
*
* @return return true or false
*/
function equal(bytes memory a, bytes memory b) pure internal returns (bool) {
return keccak256(a) == keccak256(b);
}
/**
* @dev populates a State struct instance
*
* @param input the input that is going to be put inside the State struct instance
*
* @return state returns a State struct instance
*/
function inputToState(bytes memory input) pure internal returns (State memory state)
{
state.inputHash = keccak256(input);
state.vars = KeyDeriv.pbkdf2(input, input, 128);
state.vars[0] = Salsa8.endianConvert256bit(state.vars[0]);
state.vars[1] = Salsa8.endianConvert256bit(state.vars[1]);
state.vars[2] = Salsa8.endianConvert256bit(state.vars[2]);
state.vars[3] = Salsa8.endianConvert256bit(state.vars[3]);
// This is the root hash of empty memory.
state.memoryHash = bytes32(0xe82cea94884b1b895ea0742840a3b19249a723810fd1b04d8564d675b0a416f1);
initMemory(state);
}
/**
* @dev change the state to the output format
*
* @param state the final state
*
* @return output State in output format
*/
function finalStateToOutput(State memory state, bytes memory input) pure internal returns (bytes memory output)
{
require(keccak256(input) == state.inputHash);
state.vars[0] = Salsa8.endianConvert256bit(state.vars[0]);
state.vars[1] = Salsa8.endianConvert256bit(state.vars[1]);
state.vars[2] = Salsa8.endianConvert256bit(state.vars[2]);
state.vars[3] = Salsa8.endianConvert256bit(state.vars[3]);
bytes memory val = uint4ToBytes(state.vars);
uint[4] memory values = KeyDeriv.pbkdf2(input, val, 32);
require(values[1] == 0 && values[2] == 0 && values[3] == 0);
output = new bytes(32);
uint val0 = values[0];
assembly { mstore(add(output, 0x20), val0) }
}
/**
* @dev casts a bytes32 array to a bytes array
*
* @param b the input
*
* @return r returns the bytes array
*/
function toBytes(bytes32[] memory b) pure internal returns (bytes memory r)
{
uint len = b.length * 0x20;
r = new bytes(len);
assembly {
let d := add(r, 0x20)
let s := add(b, 0x20)
for { let i := 0 } lt(i, len) { i := add(i, 0x20) } {
mstore(add(d, i), mload(add(s, i)))
}
}
}
/**
* @dev casts a bytes array into a bytes32 array
*
* @param b the input bytes array
*
* @return error Returns whether the input length module 0x20 is 0
* @return r The bytes32 array
*/
function toArray(bytes memory b) pure internal returns (bool error, bytes32[] memory r)
{
if (b.length % 0x20 != 0) {
return (true, r);
}
uint len = b.length;
r = new bytes32[](b.length / 0x20);
assembly {
let d := add(r, 0x20)
let s := add(b, 0x20)
for { let i := 0 } lt(i, len) { i := add(i, 0x20) } {
mstore(add(d, i), mload(add(s, i)))
}
}
}
/**
* @dev convert a 4-member array into a byte stream
*
* @param val the input array that has 4 members
*
* @return r the byte stream
*/
function uint4ToBytes(uint[4] memory val) pure internal returns (bytes memory r)
{
r = new bytes(4 * 32);
uint v = val[0];
assembly { mstore(add(r, 0x20), v) }
v = val[1];
assembly { mstore(add(r, 0x40), v) }
v = val[2];
assembly { mstore(add(r, 0x60), v) }
v = val[3];
assembly { mstore(add(r, 0x80), v) }
}
// Virtual functions to be implemented in either the runner/prover or the verifier.
function initMemory(State memory state) pure virtual internal;
function writeMemory(State memory state, uint index, uint[4] memory values, Proofs memory proofs) pure virtual internal;
function readMemory(State memory state, uint index, Proofs memory proofs) pure virtual internal returns (uint, uint, uint, uint);
/**
* @dev runs a single step, modifying the state.
* This in turn calls the virtual functions readMemory and writeMemory.
*
* @param state the state structure
* @param step which step to run
* @param proofs the proofs structure
*/
function runStep(State memory state, uint step, Proofs memory proofs) pure internal {
require(step < 2048);
if (step < 1024) {
writeMemory(state, step, state.vars, proofs);
state.vars = Salsa8.round(state.vars);
} else {
uint readIndex = (state.vars[2] / 0x100000000000000000000000000000000000000000000000000000000) % 1024;
(uint va, uint vb, uint vc, uint vd) = readMemory(state, readIndex, proofs);
state.vars = Salsa8.round([
state.vars[0] ^ va,
state.vars[1] ^ vb,
state.vars[2] ^ vc,
state.vars[3] ^ vd
]);
}
}
}
library Salsa8 {
uint constant m0 = 0x100000000000000000000000000000000000000000000000000000000;
uint constant m1 = 0x1000000000000000000000000000000000000000000000000;
uint constant m2 = 0x010000000000000000000000000000000000000000;
uint constant m3 = 0x100000000000000000000000000000000;
uint constant m4 = 0x1000000000000000000000000;
uint constant m5 = 0x10000000000000000;
uint constant m6 = 0x100000000;
uint constant m7 = 0x1;
/**
* @dev calculates a quarter of a slasa round on a row/column of the matrix
*
* @param y0 the first element
* @param y1 the second element
* @param y2 the third element
* @param y3 the fourth element
*
* @return the updated elements after a quarter of a salsa round on a row/column of the matrix
*/
function quarter(uint32 y0, uint32 y1, uint32 y2, uint32 y3)
pure internal returns (uint32, uint32, uint32, uint32)
{
uint32 t;
t = y0 + y3;
y1 = y1 ^ ((t * 2**7) | (t / 2**(32-7)));
t = y1 + y0;
y2 = y2 ^ ((t * 2**9) | (t / 2**(32-9)));
t = y2 + y1;
y3 = y3 ^ ((t * 2**13) | (t / 2**(32-13)));
t = y3 + y2;
y0 = y0 ^ ((t * 2**18) | (t / 2**(32-18)));
return (y0, y1, y2, y3);
}
/**
* @dev extracts a 32-bit word from the uint256 word.
*
* @param data the uint256 word from where we would like to extract a 32-bit word.
* @param word which 32-bit word to extract, 0 denotes the most signifacant 32-bit word.
*
* @return x The 32-bit extracted word
*/
function get(uint data, uint word) pure internal returns (uint32 x)
{
return uint32(data / 2**(256 - word * 32 - 32));
}
/**
* @dev shifts a 32-bit value inside a uint256 for a set amount of 32-bit words to the left
*
* @param x the 32-bit value to shift.
* @param word how many 32-bit words to shift x to the lefy by.
*
* @return A uint256 value containing x shifted to the left by word*32.
*/
function put(uint x, uint word) pure internal returns (uint) {
return x * 2**(256 - word * 32 - 32);
}
/**
* @dev calculates a slasa transposed rounds by doing the round on the rows.
*
* @param first a uint256 value containing the first half of the salsa matrix i.e. the first 8 elements.
* @param second a uint256 value containing the second half of the salsa matrix i.e. the second 8 elements.
*
* @return f The updated first half of the salsa matrix.
* @return s The updated second half of the salsa matrix.
*/
function rowround(uint first, uint second) pure internal returns (uint f, uint s)
{
(uint32 a, uint32 b, uint32 c, uint32 d) = quarter(uint32(first / m0), uint32(first / m1), uint32(first / m2), uint32(first / m3));
f = (((((uint(a) * 2**32) | uint(b)) * 2 ** 32) | uint(c)) * 2**32) | uint(d);
(b,c,d,a) = quarter(uint32(first / m5), uint32(first / m6), uint32(first / m7), uint32(first / m4));
f = (((((((f * 2**32) | uint(a)) * 2**32) | uint(b)) * 2 ** 32) | uint(c)) * 2**32) | uint(d);
(c,d,a,b) = quarter(uint32(second / m2), uint32(second / m3), uint32(second / m0), uint32(second / m1));
s = (((((uint(a) * 2**32) | uint(b)) * 2 ** 32) | uint(c)) * 2**32) | uint(d);
(d,a,b,c) = quarter(uint32(second / m7), uint32(second / m4), uint32(second / m5), uint32(second / m6));
s = (((((((s * 2**32) | uint(a)) * 2**32) | uint(b)) * 2 ** 32) | uint(c)) * 2**32) | uint(d);
}
/**
* @dev calculates a salsa column round.
*
* @param first a uint256 value containing the first half of the salsa matrix.
* @param second a uint256 value containing the second half of the salsa matrix.
*
* @return f The first half of the salsa matrix.
* @return s The second half of the salsa matrix.
*/
function columnround(uint first, uint second) pure internal returns (uint f, uint s)
{
(uint32 a, uint32 b, uint32 c, uint32 d) = quarter(uint32(first / m0), uint32(first / m4), uint32(second / m0), uint32(second / m4));
f = (uint(a) * m0) | (uint(b) * m4);
s = (uint(c) * m0) | (uint(d) * m4);
(a,b,c,d) = quarter(uint32(first / m5), uint32(second / m1), uint32(second / m5), uint32(first / m1));
f |= (uint(a) * m5) | (uint(d) * m1);
s |= (uint(b) * m1) | (uint(c) * m5);
(a,b,c,d) = quarter(uint32(second / m2), uint32(second / m6), uint32(first / m2), uint32(first / m6));
f |= (uint(c) * m2) | (uint(d) * m6);
s |= (uint(a) * m2) | (uint(b) * m6);
(a,b,c,d) = quarter(uint32(second / m7), uint32(first / m3), uint32(first / m7), uint32(second / m3));
f |= (uint(b) * m3) | (uint(c) * m7);
s |= (uint(a) * m7) | (uint(d) * m3);
}
/**
* @dev run salsa20_8 on the input matrix
*
* @param _first the first half of the input matrix to salsa.
* @param _second the sesond half of the input matrix to salsa.
*
* @return rfirst The first half of the resulting salsa matrix.
* @return rsecond The second half of the resulting salsa matrix.
*/
function salsa20_8(uint _first, uint _second) pure internal returns (uint rfirst, uint rsecond) {
uint first = _first;
uint second = _second;
for (uint i = 0; i < 8; i += 2) {
(first, second) = columnround(first, second);
(first, second) = rowround(first, second);
}
for (uint i = 0; i < 8; i++) {
rfirst |= put(get(_first, i) + get(first, i), i);
rsecond |= put(get(_second, i) + get(second, i), i);
}
}
/**
* @dev flips the endianness of a 256-bit value
*
* @param x the input
*
* @return the flipped value
*/
function endianConvert256bit(uint x) pure internal returns (uint) {
return
endianConvert32bit(x / m0) * m0 +
endianConvert32bit(x / m1) * m1 +
endianConvert32bit(x / m2) * m2 +
endianConvert32bit(x / m3) * m3 +
endianConvert32bit(x / m4) * m4 +
endianConvert32bit(x / m5) * m5 +
endianConvert32bit(x / m6) * m6 +
endianConvert32bit(x / m7) * m7;
}
/**
* @dev flips endianness for a 32-bit input
*
* @param x the 32-bit value to have its endianness flipped
*
* @return the flipped value
*/
function endianConvert32bit(uint x) pure internal returns (uint) {
return
(x & 0xff) * 0x1000000 +
(x & 0xff00) * 0x100 +
(x & 0xff0000) / 0x100 +
(x & 0xff000000) / 0x1000000;
}
/**
* @dev runs Salsa8 on input values
*
* @param values the input values for Salsa8
*
* @return returns the result of running Salsa8 on the input values
*/
function round(uint[4] memory values) pure internal returns (uint[4] memory) {
(uint a, uint b, uint c, uint d) = (values[0], values[1], values[2], values[3]);
(a, b) = salsa20_8(a ^ c, b ^ d);
(c, d) = salsa20_8(a ^ c, b ^ d);
return [a, b, c, d];
}
}
library KeyDeriv {
/**
* @dev hmacsha256
*
* @param key the key
* @param message the message to hash
*
* @return the hash result
*/
function hmacsha256(bytes memory key, bytes memory message) pure internal returns (bytes32) {
bytes32 keyl;
bytes32 keyr;
if (key.length > 64) {
keyl = sha256(key);
} else {
for (uint i = 0; i < key.length && i < 32; i++)
keyl |= bytes32(key[i]) >> (8 * i);
for (uint i = 32; i < key.length && i < 64; i++)
keyr |= bytes32(key[i]) >> (8 * (i - 32));
}
bytes32 threesix = 0x3636363636363636363636363636363636363636363636363636363636363636;
bytes32 fivec = 0x5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c;
return sha256(abi.encodePacked(fivec ^ keyl, fivec ^ keyr, sha256(abi.encodePacked(threesix ^ keyl, threesix ^ keyr, message))));
}
/// PBKDF2 restricted to c=1, hash = hmacsha256 and dklen being a multiple of 32 not larger than 128
/**
* @dev pbkdf2
*
* @param key the password
* @param salt cryptographic salt
* @param dklen desired length of the key
*
* @return r The generated key
*/
function pbkdf2(bytes memory key, bytes memory salt, uint dklen) pure internal returns (uint[4] memory r) {
bytes memory message = new bytes(salt.length + 4);
for (uint i = 0; i < salt.length; i++) {
message[i] = salt[i];
}
for (uint i = 0; i * 32 < dklen; i++) {
message[message.length - 1] = bytes1(uint8(i + 1));
r[i] = uint(hmacsha256(key, message));
}
}
}
| * @dev shifts a 32-bit value inside a uint256 for a set amount of 32-bit words to the left @param x the 32-bit value to shift. @param word how many 32-bit words to shift x to the lefy by. @return A uint256 value containing x shifted to the left by word32./ | function put(uint x, uint word) pure internal returns (uint) {
return x * 2**(256 - word * 32 - 32);
}
| 15,824,400 | [
1,
4012,
87,
279,
3847,
17,
3682,
460,
4832,
279,
2254,
5034,
364,
279,
444,
3844,
434,
3847,
17,
3682,
4511,
358,
326,
2002,
225,
619,
326,
3847,
17,
3682,
460,
358,
4654,
18,
225,
2076,
3661,
4906,
3847,
17,
3682,
4511,
358,
4654,
619,
358,
326,
22725,
93,
635,
18,
327,
432,
2254,
5034,
460,
4191,
619,
21340,
358,
326,
2002,
635,
2076,
1578,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1378,
12,
11890,
619,
16,
2254,
2076,
13,
16618,
2713,
1135,
261,
11890,
13,
288,
203,
3639,
327,
619,
380,
576,
636,
12,
5034,
300,
2076,
380,
3847,
300,
3847,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.25;
// produced by the Solididy File Flattener (c) David Appleton 2018
// contact : [email protected]
// released under Apache 2.0 licence
contract CloneFactory {
event CloneCreated(address indexed target, address clone);
function createClone(address target) internal returns (address result) {
bytes memory clone = hex"3d602d80600a3d3981f3363d3d373d3d3d363d73bebebebebebebebebebebebebebebebebebebebe5af43d82803e903d91602b57fd5bf3";
bytes20 targetBytes = bytes20(target);
for (uint i = 0; i < 20; i++) {
clone[20 + i] = targetBytes[i];
}
assembly {
let len := mload(clone)
let data := add(clone, 0x20)
result := create(0, data, len)
}
}
}
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 DeconetPaymentsSplitting {
using SafeMath for uint;
// Logged on this distribution set up completion.
event DistributionCreated (
address[] destinations,
uint[] sharesMantissa,
uint sharesExponent
);
// Logged when funds landed to or been sent out from this contract balance.
event FundsOperation (
address indexed senderOrAddressee,
uint amount,
FundsOperationType indexed operationType
);
// Enumeration of possible funds operations.
enum FundsOperationType { Incoming, Outgoing }
// Describes Distribution destination and its share of all incoming funds.
struct Distribution {
// Destination address of the distribution.
address destination;
// Floating-point number mantissa of a share allotted for a destination address.
uint mantissa;
}
// Stores exponent of a power term of a floating-point number.
uint public sharesExponent;
// Stores list of distributions.
Distribution[] public distributions;
/**
* @dev Payable fallback that tries to send over incoming funds to the distribution destinations splitted
* by pre-configured shares. In case when there is not enough gas sent for the transaction to complete
* distribution, all funds will be kept in contract untill somebody calls `withdrawFullContractBalance` to
* run postponed distribution and withdraw contract's balance funds.
*/
function () public payable {
emit FundsOperation(msg.sender, msg.value, FundsOperationType.Incoming);
distributeFunds();
}
/**
* @dev Set up distribution for the current clone, can be called only once.
* @param _destinations Destination addresses of the current payments splitting contract clone.
* @param _sharesMantissa Mantissa values for destinations shares ordered respectively with `_destinations`.
* @param _sharesExponent Exponent of a power term that forms shares floating-point numbers, expected to
* be the same for all values in `_sharesMantissa`.
*/
function setUpDistribution(
address[] _destinations,
uint[] _sharesMantissa,
uint _sharesExponent
)
external
{
require(distributions.length == 0, "Contract can only be initialized once"); // Make sure the clone isn't initialized yet.
require(_destinations.length <= 8 && _destinations.length > 0, "There is a maximum of 8 destinations allowed"); // max of 8 destinations
// prevent integer overflow when math with _sharesExponent happens
// also ensures that low balances can be distributed because balance must always be >= 10**(sharesExponent + 2)
require(_sharesExponent <= 4, "The maximum allowed sharesExponent is 4");
// ensure that lengths of arrays match so array out of bounds can't happen
require(_destinations.length == _sharesMantissa.length, "Length of destinations does not match length of sharesMantissa");
uint sum = 0;
for (uint i = 0; i < _destinations.length; i++) {
// Forbid contract as destination so that transfer can never fail
require(!isContract(_destinations[i]), "A contract may not be a destination address");
sum = sum.add(_sharesMantissa[i]);
distributions.push(Distribution(_destinations[i], _sharesMantissa[i]));
}
// taking into account 100% by adding 2 to the exponent.
require(sum == 10**(_sharesExponent.add(2)), "The sum of all sharesMantissa should equal 10 ** ( _sharesExponent + 2 ) but it does not.");
sharesExponent = _sharesExponent;
emit DistributionCreated(_destinations, _sharesMantissa, _sharesExponent);
}
/**
* @dev Process the available balance through the distribution and send money over to destination addresses.
*/
function distributeFunds() public {
uint balance = address(this).balance;
require(balance >= 10**(sharesExponent.add(2)), "You can not split up less wei than sum of all shares");
for (uint i = 0; i < distributions.length; i++) {
Distribution memory distribution = distributions[i];
uint amount = calculatePayout(balance, distribution.mantissa, sharesExponent);
distribution.destination.transfer(amount);
emit FundsOperation(distribution.destination, amount, FundsOperationType.Outgoing);
}
}
/**
* @dev Returns length of distributions array
* @return Length of distributions array
*/
function distributionsLength() public view returns (uint256) {
return distributions.length;
}
/**
* @dev Calculates a share of the full amount.
* @param _fullAmount Full amount.
* @param _shareMantissa Mantissa of the percentage floating-point number.
* @param _shareExponent Exponent of the percentage floating-point number.
* @return An uint of the payout.
*/
function calculatePayout(uint _fullAmount, uint _shareMantissa, uint _shareExponent) private pure returns(uint) {
return (_fullAmount.div(10 ** (_shareExponent.add(2)))).mul(_shareMantissa);
}
/**
* @dev Checks whether or not a given address contains a contract
* @param _addr The address to check
* @return A boolean indicating whether or not the address is a contract
*/
function isContract(address _addr) private view returns (bool) {
uint32 size;
assembly {
size := extcodesize(_addr)
}
return (size > 0);
}
}
contract DeconetPaymentsSplittingFactory is CloneFactory {
// PaymentsSplitting master-contract address.
address public libraryAddress;
// Logged when a new PaymentsSplitting clone is deployed to the chain.
event PaymentsSplittingCreated(address newCloneAddress);
/**
* @dev Constructor for the contract.
* @param _libraryAddress PaymentsSplitting master-contract address.
*/
constructor(address _libraryAddress) public {
libraryAddress = _libraryAddress;
}
/**
* @dev Create PaymentsSplitting clone.
* @param _destinations Destination addresses of the new PaymentsSplitting contract clone.
* @param _sharesMantissa Mantissa values for destinations shares ordered respectively with `_destinations`.
* @param _sharesExponent Exponent of a power term that forms shares floating-point numbers, expected to
* be the same for all values in `_sharesMantissa`.
*/
function createPaymentsSplitting(
address[] _destinations,
uint[] _sharesMantissa,
uint _sharesExponent
)
external
returns(address)
{
address clone = createClone(libraryAddress);
DeconetPaymentsSplitting(clone).setUpDistribution(_destinations, _sharesMantissa, _sharesExponent);
emit PaymentsSplittingCreated(clone);
return clone;
}
} | Stores exponent of a power term of a floating-point number. | uint public sharesExponent;
| 14,015,401 | [
1,
13125,
9100,
434,
279,
7212,
2481,
434,
279,
13861,
17,
1153,
1300,
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,
2254,
1071,
24123,
17972,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x2C39BB41E2af6BeC6c3Bb102c07C15eda648A366/sources/src/TokenUriResolver.sol | * @notice Set the default IJBTokenUriResolver. @dev Only available to this contract's owner. @param _resolver The address of the default token uri resolver./ | function setDefaultTokenUriResolver(IJBTokenUriResolver _resolver) external onlyOwner {
tokenUriResolvers[0] = IJBTokenUriResolver(_resolver);
emit DefaultTokenUriResolverSet(_resolver);
}
| 4,343,830 | [
1,
694,
326,
805,
467,
8877,
1345,
3006,
4301,
18,
225,
5098,
2319,
358,
333,
6835,
1807,
3410,
18,
225,
389,
14122,
1021,
1758,
434,
326,
805,
1147,
2003,
5039,
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,
565,
445,
9277,
1345,
3006,
4301,
12,
45,
8877,
1345,
3006,
4301,
389,
14122,
13,
3903,
1338,
5541,
288,
203,
3639,
1147,
3006,
28715,
63,
20,
65,
273,
467,
8877,
1345,
3006,
4301,
24899,
14122,
1769,
203,
203,
3639,
3626,
2989,
1345,
3006,
4301,
694,
24899,
14122,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity >0.7.4;
contract who{
//Direcció del propietari de l'smart contract de l'Organització Mundial de la Salut
address owner = 0x959FD7Ef9089B7142B6B908Dc3A8af7Aa8ff0FA1;
//Definició de variables
address SC_WHO;
address[] public Active_Labs;
address[] public Active_Users;
uint256 numRequests = 0;
//Definició de mappings
mapping (uint256 => request) public requests;
mapping (address => struct_Lab) public Lab;
mapping (address => address) public userSC;
//Definició d'estructures
struct struct_Lab{
string name;
bool active;
address sc_adr;
}
struct request{
bool resolved;
address alice_address;
address entity;
}
//Constructor
constructor(){
SC_WHO = address(uint160(address(this)));
}
//------ FUNCIONS ------
//------ Gestió de laboratoris------
//Registre d'un nou laboratori al sistema
event newLab(string labName, address adr_lab);
function registerLab(address payable _lab, string memory _name) public onlyOwner() {
Lab[_lab].sc_adr = address(new lab(_lab, SC_WHO));
Active_Labs.push(_lab);
Lab[_lab].name=_name;
Lab[_lab].active = true;
emit newLab(_name, _lab);
}
//Baixa d'un laboratori (destrucció de l'smart contract)
event labDeleted(address adr_lab, string labname);
function deleteLab(address _lab, address _sc_adr) public onlyOwner(){
Lab[_lab].active = false;
lab(_sc_adr).destruct();
string storage labname = Lab[_lab].name;
emit labDeleted(_lab, labname);
}
//Nombre de laboratoris registrats
function getLabsCount()public view onlyOwner() returns(uint256){
return Active_Labs.length;
}
//Nom d'un laboratori registrat
/*function getLabName(address adr_Lab) public view onlyOwner() returns(string memory){
return Lab[adr_Lab].name;
}
//Estat d'un laboratori registrat (actiu - inactiu)
function getLabState(address adr_Lab) public view onlyOwner() returns(bool){
return Lab[adr_Lab].active;
}*/
function getLabInfo(address adr_Lab) public view onlyOwner()returns(string memory, bool){
return (Lab[adr_Lab].name, Lab[adr_Lab].active);
}
//Smart contract d'un laboratori registrat
function getLabSC(address adr_Lab) public view returns(address){
return Lab[adr_Lab].sc_adr;
}
//------ Gestió d'usuaris ------
//Registre d'un nou usuari
event new_User(address);
function registerUser(address _owner, string memory _pubKey) external returns (address) {
address userOwner = _owner;
address sc_adr = address(new user(userOwner, _pubKey, SC_WHO));
Active_Users.push(userOwner);
userSC[userOwner] = sc_adr;
emit new_User(userOwner);
return (sc_adr);
}
//Obtenció de l'adreça de l'smart contract d'un usuari
function getUserSC(address adr_User) public view returns(address){
return userSC[adr_User];
}
//Solicitud externa d'un certificat d'un usuari
function getAliceDocs(address _alices_address, address _entity_address) public onlyUser(){
requests[numRequests].alice_address = _alices_address;
requests[numRequests].entity = _entity_address;
requests[numRequests].resolved = false;
address entitySC = userSC[_entity_address];
if(user(entitySC).getEntity()){
who(SC_WHO).resolveAliceDocs(numRequests);
}
numRequests = numRequests + 1;
}
//Resolució d'una sol·licitud
function resolveAliceDocs(uint256 _identifier) public onlyOwner(){
address aliceAdr = requests[_identifier].alice_address;
address aliceSC = userSC[aliceAdr];
address entitat = requests[_identifier].entity;
requests[_identifier].resolved = true;
user(aliceSC).newSol(entitat);
}
//Denegació d'una sol·licitud
function denySol(uint256 _identifier) public onlyOwner(){
requests[_identifier].resolved = true;
}
//Obtenció del nombre de peticions existents
function getNumRequests() public view onlyOwner() returns(uint256) {
return numRequests;
}
//Obtenció de la informació correponent a una sol·licitud
function obtainRequests(uint256 _identifier) public view onlyOwner() returns(address alice_address, address entityReq) {
if(!requests[_identifier].resolved){
return (requests[_identifier].alice_address, requests[_identifier].entity);
}
}
//Gestió d'entitats
//Activació/Desactivació de l'atribut d'entitat fiable
event entity(address, bool);
function Entity(bool active, address _entityAdr) public onlyOwner(){
address entitySC = userSC[_entityAdr];
user(entitySC).activeEntity(active);
emit entity(_entityAdr, active);
}
// Modifier
modifier onlyOwner(){
require(msg.sender == owner || msg.sender == SC_WHO, "L'adresa que ha realitzat la crida no te els permissos de propietat.");
_;
}
modifier onlyUser(){
require(getUserSC(msg.sender) != 0x0000000000000000000000000000000000000000, "L'adresa que ha realitzat la crida no te els permissos de propietat.");
_;
}
}
contract lab{
//Definició de variables
address payable owner;
string hashA;
address whoSC_Addr;
//------ FUNCIONS ------
//Constructor de l'smart contract
constructor(address payable _lab, address _whoSC_Addr){
owner = _lab;
whoSC_Addr = _whoSC_Addr;
}
//Càrrega d'un nou document a l'smart contract d'un usuari del sistema
event newDocument(address);
function uploadCert(address _alice_SC_Adr, string memory _hashDoc, string memory _capsule) public onlyOwner(){
user(_alice_SC_Adr).newDoc(_hashDoc, _capsule);
emit newDocument(_alice_SC_Adr);
}
//Funció de baixa del laboratori, destrucció de l'smart contract
event labRemoval(address);
function destruct()external onlyWHO(){
emit labRemoval(owner);
selfdestruct(owner);
}
function getOwner() public view returns(address labOwner){
return owner;
}
//------MODIFIERS------
modifier onlyOwner(){
require(msg.sender == owner, "L'adresa que ha realitzat la crida no te els permissos de propietat.");
_;
}
modifier onlyWHO(){
require(msg.sender == whoSC_Addr, "L'adresa que ha realitzat la crida no te els permissos de propietat.");
_;
}
}
contract user{
//Definició de variables
string pubKey;
string [] public docs;
string [] public capsule;
string [] public extDocs;
//address sc_adr;
address owner;
address whoSC_Addr;
bool entity;
uint256 numRequests = 0;
//Definició de mappings
mapping (string => uint256) public indexDocs;
mapping (string => externalDocParams) public extDocParams;
mapping (uint256 => request) public requests;
//Definició d'estructures
struct request{
bool resolved;
address entity_address;
}
struct externalDocParams{
string exthash;
string extPubKey;
string capsule;
string kfrag0;
string verifyingKey;
}
//------FUNCIONS------
//Constructor
constructor(address _owner, string memory _pubKey, address _whoSC_Addr) {
owner = _owner;
whoSC_Addr = _whoSC_Addr;
pubKey = _pubKey;
entity = false;
}
//------Gestió de la clau d'encriptació pública de l'usuari------
//Obtenció de la clau pública de l'usuari
function getPubKey() view public returns(string memory publicKey){
return (pubKey);
}
//Introducció d'una nova clau pública, per a substituir l'anterior
/*function newPubKey(string memory _pubKey) public onlyOwner(){
pubKey = _pubKey;
}*/
//------Gestió de certificats------
//Introducció d'un nou certificats, execució des d'un laboratori del sistema
function newDoc(string memory _hash, string memory _capsule) public onlyLab(){
uint256 index= docs.length;
indexDocs[_hash] = index;
capsule.push(_capsule);
docs.push(_hash);
}
//Introducció d'un certificat extern, propietat d'un altre usuari del sistema
function newExtDoc(string memory _hash, string memory _pubKeyUser, string memory _capsule, string memory _kfrag0, string memory _alicesVerifyingKey) public onlyUser(){
extDocs.push(_hash);
extDocParams[_hash].extPubKey = _pubKeyUser;
extDocParams[_hash].capsule = _capsule;
extDocParams[_hash].kfrag0 = _kfrag0;
extDocParams[_hash].verifyingKey = _alicesVerifyingKey;
}
//Funcions per a l'obtenció dels paràmetres que defineixen els diferents certificats emmagatzemats a l'smart contract
function getIndexDoc(string memory _hash) public view onlyOwner() returns (uint256 index){
return indexDocs[_hash];
}
function getDocsInfo(uint _index) public view onlyOwner() returns(string memory, string memory){
return (docs[_index], capsule[_index]);
}
/*function getDocsHash(uint _index) public view onlyOwner() returns(string memory){
return docs[_index];
}
function getDocsCapsule(uint _index) public view onlyOwner() returns (string memory){
return capsule[_index];
}*/
function getExtDocs(uint _index) public view onlyOwner() returns(string memory) {
return extDocs[_index];
}
function getExtInfo(string memory _hash) public view onlyOwner() returns (string memory, string memory, string memory, string memory){
return (extDocParams[_hash].extPubKey, extDocParams[_hash].capsule, extDocParams[_hash].kfrag0, extDocParams[_hash].verifyingKey);
}
//Funcions per obtenir el nombre de documents tant propietat de l'usuari com externs
function lengthDocArray() public view onlyOwner() returns(uint){
return docs.length;
}
function lengthExtDocArray() public view onlyOwner() returns(uint){
return extDocs.length;
}
//------Gestió d'entitat------
//Activació / desactivació de la característica d'entitat
function activeEntity(bool _active) public onlyWHO() {
entity = _active;
}
//Obtenció del valor de la característica d'entitat (activa o inactiva)
function getEntity()public view returns (bool){
return entity;
}
//------Gestió de sol·licituds externes------
//Introducció d'una nova sol·licitud d'enviament de certificat
function newSol(address _entityAdr) public onlyWHO() {
requests[numRequests].entity_address = _entityAdr;
requests[numRequests].resolved = false;
numRequests = numRequests + 1;
}
//Resolució d'una sol·licitud
function resolveSol(uint256 _identifier) public onlyOwner(){
requests[_identifier].resolved = true;
}
//Obtenció d'una petició emmagatzemada a l'smart contract
function obtainRequests(uint256 _identifier) public view onlyOwner() returns(address entityReq) {
if(!requests[_identifier].resolved){
return (requests[_identifier].entity_address);
}
}
//Obtenció del nombre de peticions total
function getNumRequests() public view onlyOwner() returns(uint256) {
return numRequests;
}
//------MODIFIERS------
modifier onlyOwner(){
require(msg.sender == owner, "L'adresa que ha realitzat la crida no te els permissos de propietat.");
_;
}
modifier onlyWHO(){
require(msg.sender == whoSC_Addr, "L'adresa que ha realitzat la crida no te els permissos de propietat.");
_;
}
modifier onlyLab(){
address lab_owner = lab(msg.sender).getOwner();
require(who(whoSC_Addr).getLabSC(lab_owner) != 0x0000000000000000000000000000000000000000, "L'adresa que ha realitzat la crida no te els permissos de propietat.");
_;
}
modifier onlyUser(){
require(who(whoSC_Addr).getUserSC(msg.sender) != 0x0000000000000000000000000000000000000000, "L'adresa que ha realitzat la crida no te els permissos de propietat.");
_;
}
} | Denegació d'una sol·licitud | function denySol(uint256 _identifier) public onlyOwner(){
requests[_identifier].resolved = true;
}
| 5,473,946 | [
1,
8517,
1332,
1077,
77,
132,
116,
302,
11,
31172,
3704,
131,
120,
80,
335,
305,
1100,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
17096,
20608,
12,
11890,
5034,
389,
5644,
13,
1071,
1338,
5541,
1435,
95,
203,
3639,
3285,
63,
67,
5644,
8009,
11792,
273,
638,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../token/IERC20MintableDetailed.sol";
import "../state/StateMachine.sol";
import "../math/DecimalMath.sol";
/**
* @title Issuance
* @notice Implements a very simple issuance process for tokens
*
* 1. Initialize contract with the issuance token contract address. This address must inherit from `ERC20Mintable` and `ERC20Detailed`.
* 2. Use `setIssuePrice` to determine how many ether (in wei) do investors
* have to pay for each issued token.
* 3. Use `startIssuance` to allow investors to invest.
* 4. Investors can `invest` their ether at will.
* 5. Investors can also `cancelInvestment` and get their ether back.
* 6. The contract owner can `cancelAllInvestments` to close the investment phase.
* In this case `invest` is not available, but `cancelInvestment` is.
* 7. Use `startDistribution` to close the investment phase.
* 8. Investors can only `claim` their issued tokens now.
* 9. Owner can use `withdraw` to send collected ether to a wallet.
*/
contract IssuanceEth is Ownable, StateMachine, ReentrancyGuard {
using SafeMath for uint256;
using DecimalMath for uint256;
event IssuanceCreated();
event IssuePriceSet();
event InvestmentAdded(address investor, uint256 amount);
event InvestmentCancelled(address investor, uint256 amount);
address public issuanceToken;
address[] public investors;
mapping(address => uint256) public investments;
uint256 public amountRaised;
uint256 public amountWithdrawn;
uint256 public issuePrice;
constructor(
address _issuanceToken
) public Ownable() StateMachine() {
issuanceToken = _issuanceToken;
_createTransition("SETUP", "OPEN");
_createTransition("OPEN", "LIVE");
_createTransition("OPEN", "FAILED");
emit IssuanceCreated();
}
/**
* @notice Use this function to claim your issuance tokens
* @dev Each user will call this function on his behalf
*/
function claim() external virtual nonReentrant {
require(
currentState == "LIVE",
"Cannot claim now."
);
require(
investments[msg.sender] > 0,
"No investments found."
);
uint256 amount = investments[msg.sender];
investments[msg.sender] = 0;
IERC20MintableDetailed _issuanceToken = IERC20MintableDetailed(
issuanceToken
);
_issuanceToken.mint(
msg.sender,
amount.divd(issuePrice, _issuanceToken.decimals())
);
}
/**
* @dev Function for an investor to cancel his investment
*/
function cancelInvestment() external virtual nonReentrant {
require (
currentState == "OPEN" || currentState == "FAILED",
"Cannot cancel now."
);
require(
investments[msg.sender] > 0,
"No investments found."
);
uint256 amount = investments[msg.sender];
investments[msg.sender] = 0;
msg.sender.transfer(amount);
emit InvestmentCancelled(msg.sender, amount);
}
/**
* @notice Invest into the issuance by sending ether to this function
*/
function invest() public virtual payable {
require(
currentState == "OPEN",
"Not open for investments."
);
require(
msg.value.mod(issuePrice) == 0,
"Fractional investments not allowed."
);
if (investments[msg.sender] == 0){
investors.push(msg.sender);
}
investments[msg.sender] = investments[msg.sender].add(msg.value);
amountRaised = amountRaised.add(msg.value);
emit InvestmentAdded(msg.sender, msg.value);
}
/**
* @dev Function to open the issuance to investors
*/
function startIssuance() public virtual onlyOwner {
require(
issuePrice > 0,
"Issue price not set."
);
_transition("OPEN");
}
/**
* @dev Function to move to the distributing phase
*/
function startDistribution() public virtual onlyOwner {
_transition("LIVE");
}
/**
* @dev Function to cancel all investments
*/
function cancelAllInvestments() public virtual onlyOwner{
_transition("FAILED");
}
/**
* @dev Function to transfer all collected tokens to the wallet of the owner
*/
function withdraw(address payable _wallet)
public
virtual
onlyOwner
nonReentrant
{
require(
currentState == "LIVE",
"Cannot withdraw funds now."
);
uint256 amount = amountRaised - amountWithdrawn;
amountWithdrawn = amount;
_wallet.transfer(amount);
}
function setIssuePrice(uint256 _issuePrice) public virtual onlyOwner {
require(
currentState == "SETUP",
"Cannot setup now."
);
issuePrice = _issuePrice;
emit IssuePriceSet();
}
} | * @dev Function to open the issuance to investors/ | function startIssuance() public virtual onlyOwner {
require(
issuePrice > 0,
"Issue price not set."
);
_transition("OPEN");
}
| 12,907,322 | [
1,
2083,
358,
1696,
326,
3385,
89,
1359,
358,
2198,
395,
1383,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
787,
7568,
89,
1359,
1435,
1071,
5024,
1338,
5541,
288,
203,
3639,
2583,
12,
203,
5411,
5672,
5147,
405,
374,
16,
203,
5411,
315,
12956,
6205,
486,
444,
1199,
203,
3639,
11272,
203,
3639,
389,
14936,
2932,
11437,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
// import "https://github.com/Scott6768/LottoescapeV2/blob/main/LottoescapeV2";
import "./LSC.sol";
//import "";
contract LottoGame {
uint perTicketPrice;
using SafeMath for uint256;
address[5] winners; //payable[] public winners;
uint public numWinners;
bool terminator; //flag for stopping the game in its tracks
uint public potValue;
uint public potRemaining;
mapping(address => uint) public ticketBalance;
mapping(address => uint) public profits;
uint public totalTickets;
address public owner;
address internal _tokenAddress;
uint public amountToSendToNextRound;
uint amountToMarketingAddress;
uint amountToSendToLiquidity;
//uint public timeLeft;
uint public startTime;
uint public endTime;
uint public roundNumber; // to keep track of the active round of play
address public liquidityTokenRecipient;
LSC public token;
IPancakeRouter02 public pancakeswapV2Router;
uint256 minimumBuy; //minimum buy to be eligible to win share of the pot
uint256 tokensToAddOneSecond; //number of tokens that will add one second to the timer
uint256 maxTimeLeft; //maximum number of seconds the timer can be
uint256 maxWinners; //number of players eligible for winning share of the pot
uint256 potPayoutPercent; // what percent of the pot is paid out
uint256 potLeftoverPercent; // what percent is leftover
uint256 maxTickets; // max amount of tickets a player can hold
uint[5] winnerProfits;
uint[5] bnbProfits;
//optional stuff for fixing code later
address public _liquidityAddress = 0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3; //set to proper address if you need to pull V2 router manually
address public _marketingAddress = 0x54b360304374156D80C49b97a820836f89655360; //set to proper marketing address
constructor() public {
_tokenAddress = 0x2c0B1c005c54924eB53B4C3fD1650690BA01C128;
token = LSC(payable(_tokenAddress));
//pancakeswapV2Router = 0xB8D16214aD6Cb0E4967c3aeFCc8Bc5f74D386B0a; //The lazy way
pancakeswapV2Router = token.pancakeswapV2Router(); // pulls router information directly from main contract
// BUT, JUST IN CAST ^^THAT DOESN'T WORK:
/*/ Taken from standard code base, you also might try pulling v2pair and running with that.
IPancakeRouter02 _pancakeswapV2Router = IPancakeRouter02(_liquidityAddress);
//Create a Pancake pair for this new token
address pancakeswapV2Pair = IPancakeFactory(_pancakeswapV2Router.factory())
.createPair(address(this), _pancakeswapV2Router.WETH());
//set the rest of the contract variables
pancakeswapV2Router = _pancakeswapV2Router;
//*/
owner = msg.sender;
//liquidityTokenRecipient = address(this);
liquidityTokenRecipient = _liquidityAddress;
//set initial game gameSettings
minimumBuy = 100000*10**9;
tokensToAddOneSecond = 1000*10**9;
maxTimeLeft = 300 seconds;
maxWinners = 5;
potPayoutPercent = 60;
potLeftoverPercent = 40;
maxTickets = 10;
}
receive() external payable {
//to be able to receive eth/bnb
}
function getGameSettings() public view returns (uint, uint, uint, uint, uint) {
return (minimumBuy, tokensToAddOneSecond, maxTimeLeft, maxWinners, potPayoutPercent);
}
function adjustBuyInAmount(uint newBuyInAmount) external {
//add new buy in amount with 9 extra zeroes when calling this function (your token has 9 decimals)
require(msg.sender == owner, "Only owner");
minimumBuy = newBuyInAmount;
}
function transferOwnership(address newOwner) external {
require(msg.sender == owner, "Only owner.");
require(newOwner != address(0), "Address of owner cannot be zero.");
owner = newOwner;
}
function changeLiqduidityTokenRecipient(address newRecipient) public {
require(msg.sender == owner, "Only owner");
require(newRecipient != address(0), "Address of recipient cannot be zero.");
_liquidityAddress = newRecipient;
liquidityTokenRecipient = _liquidityAddress;
}
function buyTicket(address payable buyer, uint amount) public {
require(endTime != 0, "Game is not active!"); // will set when owner starts the game with initializeAndStart()
require(amount >= minimumBuy, "You must bet a minimum of 100,000 tokens.");
require(amount.div(minimumBuy * 10) <= maxTickets, "You may only purchase 10 tickets per play");
require(token.balanceOf(msg.sender) >= amount, "You don't have enough tokens"); //check the owners wallet to make sure they have enough
//note this function will throw unless a ticket is purchased!!
// start a new round if needed
uint startflag = getTimeLeft();
// getTimeLeft() returns 0 if the game has ended
if (startflag == 0) {
endGame();
} else { //if startflag is NOT equal to zero, game carries on
bool alreadyPlayed = false; //set this as a flag inside of the if
for (uint i = 0; i < numWinners; i++) { //scroll through the winners list
if (buyer == winners[i]){
alreadyPlayed = true;
}
}
//This statement is the whole point of the ELSE block, just make sure they aren't on the board
//If you need to remove their previous bet and add a new one, do it here.
//add a flag above for the index and squish it.
require(alreadyPlayed == false, "You can only buy tickets if you don't have a valid bid on the board");
}
ticketBalance[buyer] += amount.div(100000*10**9);
require(ticketBalance[buyer] >= 1, "Not enough for a ticket");
if (numWinners < maxWinners) {
// Only 5 winners allowed on the board, so if we haven't met that limit then add to the stack
winners[numWinners] = payable(buyer);
numWinners++;
} else {
//add new buyer and remove the first from the stack
ticketBalance[winners[0]] = 0;
for (uint i=0; i < (maxWinners - 1); i++){ //note the -1, we only want the leading values
winners[i] = winners[i+1];
}
winners[numWinners - 1] = payable(buyer); //now we add the stake to the top
}
uint timeToAdd = amount.div(tokensToAddOneSecond);
addTime(timeToAdd);
// Transfer Approval is handled by Web 3 before sending
// approve(this contract, amount)
token.transferFrom(msg.sender, payable(address(this)), amount);
//token.transferLSCgame2(msg.sender, payable(address(this)), amount);
potValue += amount;
}
function localTokenBalance() public view returns(uint){
return token.balanceOf(address(this));
}
function getTimeLeft() public view returns (uint){
if (now >= endTime) {
//endGame(); This would cost gas for the calling wallet or function, not good, but it would be an auto-start not requiring a new bid
// IF this returns 0, then you can add the "Buy ticket to start next round" and the gas from that ticket will start the next round
// see buyTicket for details
return 0;
}else
return endTime - now;
}
function addTime(uint timeAmount) private {
endTime += timeAmount;
if ((endTime - now) > maxTimeLeft) {
endTime = now + maxTimeLeft;
}
}
function initializeAndStart() external {
require(msg.sender == owner, "Only the contract owner can start the game");
roundNumber = 0;
startGame();
}
function startGame() private {
require(endTime <= now, "Stop spamming the start button please.");
roundNumber++;
startTime = now;
endTime = now + maxTimeLeft;
winners = [address(0), address(0), address(0), address(0), address(0)];
numWinners = 0;
}
function endGame() private {
require(now >= endTime, "Game is still active");
potRemaining = setPayoutAmount(); //does not change pot Value
require (potRemaining > 0, "potRemaining is 0!");
dealWithLeftovers(potRemaining);
sendProfitsInBNB();
swapAndAddLiqduidity();
potValue = amountToSendToNextRound;
if (amountToMarketingAddress > 0) {
// token.transfer(payable(_marketingAddress), (amountToMarketingAddress));
token.transferLSCgame2(address(this), payable(_marketingAddress), (amountToMarketingAddress));
}
for (uint i = 0; i < numWinners; i++) {
ticketBalance[winners[i]] = 0;
winners[i] = address(0);
}
if (terminator == false){
startGame();
} else { terminator = false; }
}
function setPayoutAmount() private returns(uint){
//get number of tickets held by each winner in the array
//only run once per round or tickets will be incorrectly counted
//this is handled by endGame(), do not call outside of that pls and thnx
totalTickets = 0; //reset before you start counting
for (uint i = 0; i < numWinners; i++) {
totalTickets += ticketBalance[winners[i]];
}
//require (totalTickets > 0, "Total Tickets is 0!");
//uint perTicketPrice;
uint top = (potValue.mul(potPayoutPercent));
uint bottom = (totalTickets.mul(100));
//require(bottom > 0, "Something has gone horribly wrong.");
if (bottom > 0){
perTicketPrice = top / bottom;
}
uint tally = 0;
//calculate the winnings based on how many tickets held by each winner
for (uint i; i < numWinners; i++){
winnerProfits[i] = perTicketPrice * ticketBalance[winners[i]];
tally += winnerProfits[i];
if (winnerProfits[i] > 0) {
bnbProfits[i] = swapProfitsForBNB(winnerProfits[i]);
}
}
require (tally < potValue, "Tally is bigger than the pot!");
return (potValue - tally);
}
function preLoadPot(uint amount) public { //This needs to be fixed also
//token.outsideApprove(msg.sender, address(this), amount);
// token.transferFrom(msg.sender, payable(address(this)), amount);
token.transferLSCgame2(msg.sender, payable(address(this)), amount);
potValue += amount;
}
function swapProfitsForBNB(uint amount) private returns (uint256) {
address[] memory path = new address[](2);
path[0] = _tokenAddress;
//path[0] = address(this);
path[1] = pancakeswapV2Router.WETH();
//token.gameApprove(address(this), address(pancakeswapV2Router), amount);
token.approve(address(pancakeswapV2Router), amount);
uint256 startingAmount = address(this).balance;
// make the swap
pancakeswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
amount,
0, // accept any amount of ETH
path,
//_tokenAddress,
payable(address(this)),
block.timestamp
);
return address(this).balance - startingAmount;
}
//send bnb amount
function sendProfitsInBNB() private {
for (uint i; i < numWinners; i++){
payable(winners[i]).transfer(bnbProfits[i]);
}
}
function dealWithLeftovers(uint leftovers) private {
require(leftovers > 100, "no leftovers to spend");
require(potRemaining > 100, "no leftovers to spend");
uint nextRoundPot = 25;
uint liquidityAmount = 5;
uint marketingAddress = 10;
//There could potentially be some rounding error issues with this, but the sheer number of tokens
//should keep any problems to a minium.
// Fractions are set up as parts from the leftover 40%
amountToSendToNextRound = (potRemaining * nextRoundPot);
amountToSendToNextRound = amountToSendToNextRound.div(40);
amountToSendToLiquidity = (potRemaining * liquidityAmount);
amountToSendToLiquidity = amountToSendToLiquidity.div(40);
amountToMarketingAddress = (potRemaining * marketingAddress);
amountToMarketingAddress = amountToMarketingAddress.div(40);
}
//Send liquidity
function swapAndAddLiqduidity() private {
//sell half for bnb
uint halfOfLiqduidityAmount = amountToSendToLiquidity.div(2);
//first swap half for BNB
address[] memory path = new address[](2);
path[0] = _tokenAddress;
//path[0] = payable(address(this));
path[1] = pancakeswapV2Router.WETH();
//approve pancakeswap to spend tokens
token.approve(address(pancakeswapV2Router), halfOfLiqduidityAmount);
//get the initial contract balance
uint256 ethAmount = address(this).balance;
//swap if there is money to Send
if (amountToSendToLiquidity > 0) {
pancakeswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
halfOfLiqduidityAmount,
0, // accept any amount of BNB
path,
//_tokenAddress, //tokens get swapped to this contract so it has BNB to add liquidity
payable(address(this)),
block.timestamp + 30 seconds //30 second limit for the swap
);
ethAmount = address(this).balance - ethAmount;
//now we have BNB, we can add liquidity to the pool
token.approve(address(pancakeswapV2Router), halfOfLiqduidityAmount);
pancakeswapV2Router.addLiquidityETH {value: ethAmount} (
_tokenAddress, //token address
halfOfLiqduidityAmount, //amount to send
0, // slippage is unavoidable
0, // slippage is unavoidable
liquidityTokenRecipient, // where to send the liqduity tokens
block.timestamp + 30 seconds //deadline
);
}
}
// Fallback function is called when msg.data is not empty
fallback() external payable {}
function getRound() external view returns(uint){
return roundNumber;
}
// ******************8 Sane functions for export to front end
function totalPotValue() external view returns(uint){
return potValue;
}
function getWinners() external view returns(address, address, address, address, address){
return (winners[0], winners[1], winners[2], winners[3], winners[4]);
}
function getTicketsPerWinner() external view returns(uint, uint, uint, uint, uint)
{
//the ratio of payout is contingent on how many tickets that winner is holding vs the rest
return (ticketBalance[winners[0]], ticketBalance[winners[1]], ticketBalance[winners[2]], ticketBalance[winners[3]], ticketBalance[winners[4]]);
}
function setTokenAddress(address newAddress) external {
require(msg.sender == owner);
_tokenAddress = newAddress;
token = LSC(payable(_tokenAddress));
}
function getTokenAddress() external view returns(address) {
return _tokenAddress;
}
function getEndTime() external view returns(uint){
//Return the end time for the game in UNIX time
return endTime;
}
function updatePancakeRouterInfo() external {
require(msg.sender == owner);
pancakeswapV2Router = token.pancakeswapV2Router(); // pulls router information directly from main contract
}
function setMarketingAddress(address _newAddress) external {
require(msg.sender == owner);
_marketingAddress = _newAddress;
}
function getMarketingAddress() external view returns(address) {
return _marketingAddress;
}
function terminateGame() external {
require(msg.sender == owner, "Only the contract owner can terminate the game");
terminator = true;
endGame();
}
} | what percent is leftover
| uint256 potLeftoverPercent; | 7,282,713 | [
1,
23770,
5551,
353,
29709,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
5974,
1682,
74,
24540,
8410,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
import './interface/IAurumOracleCentralized.sol';
contract AurumOracleCentralized is IAurumOracleCentralized {
//Using TWAP model, using index for looping and re-write the price storage
address public admin; // Admin can initiate price and set manager (reducing risk of privatekey leak) Admin private key store in Hardware wallet.
address public manager; // Manager can update the price, using Multi-signature wallet address to reduce risk of single key leak.
address busd; //Reference stable coin price.
struct PriceList {
uint128[6] avgPrice;
uint128[6] timestamp;
uint8 currentIndex;
}
mapping (address => bool) alreadyInit;
bool goldInit;
mapping (address => PriceList) asset;
PriceList goldPrice; // gold price TWAP
ISlidingWindow public slidingWindow;
// Period range will trigger the alarm when someone got the admin private key and try to manipulate prices
//
uint public periodRange = 60*50; // 50 minutes
function isPriceOracle() external pure returns (bool) {return true;}
address WREI; // Wrapped REI address
constructor (address WREI_, address busd_) {
admin = msg.sender;
busd = busd_;
WREI = WREI_; // WREI will prevent crash when query the 'lendREI' token
}
modifier onlyAdmin {
require(msg.sender == admin, "Only admin");
_;
}
modifier onlyManager {
require(msg.sender == manager, "Only manager");
_;
}
error RepeatedInit(address token);
event Initialized_Asset(address token, uint128 price, uint128 timestamp);
event Initialized_Gold(uint128 price, uint128 timestamp);
event SetNewAdmin(address oldAdmin, address newAdmin);
event SetNewManager(address oldManager, address newManager);
event SetNewSlidingWindow(address oldSlidingWindow, address newSlidingWindow);
// Initialized Asset before updateAssetPrice, make sure that lastPrice not equal to 0, and Timestamp not equal to 0.
function initializedAsset(address token, uint128 price) external onlyAdmin{
if(alreadyInit[token]){
revert RepeatedInit(token);
}
uint8 i;
uint128 currentTime = uint128(block.timestamp);
for(i=0;i<6;i++){
asset[token].avgPrice[i] = price;
asset[token].timestamp[i] = currentTime;
}
asset[token].currentIndex = 0;
alreadyInit[token] = true;
emit Initialized_Asset(token, price, currentTime);
}
function initializedGold(uint128 price) external onlyAdmin{
if(goldInit){
revert RepeatedInit(address(0));
}
uint8 i;
uint128 currentTime = uint128(block.timestamp);
for(i=0;i<6;i++){
goldPrice.avgPrice[i] = price;
goldPrice.timestamp[i] = currentTime;
}
goldPrice.currentIndex = 0;
goldInit = true;
emit Initialized_Gold(price, currentTime);
}
// Update price with the TWAP model.
function updateAssetPrice(address token, uint128 price) external onlyManager{
uint8 index = asset[token].currentIndex;
uint8 lastIndex;
uint8 nextIndex;
if(index == 0){
lastIndex = 5;
} else {
lastIndex = index-1;
}
uint lastPrice = asset[token].avgPrice[lastIndex];
if(index == 5){
nextIndex = 0;
} else {
nextIndex = index+1;
}
//newDeltaTime is the time n - time K // it must more than period time
//oldDeltaTime is the time K - time 0
uint newDeltaTime = block.timestamp - asset[token].timestamp[lastIndex];
require(newDeltaTime >= periodRange, "update too early"); //If update oracle bot catch this means the privatekey got hacked OR the bot error.
uint oldDeltaTime = asset[token].timestamp[lastIndex]-asset[token].timestamp[nextIndex]; // This need to be initialized
//new AvgPrice is ( price*tk + price*tn ) / tk+tn
uint newAvgPrice = ((oldDeltaTime*lastPrice) + (newDeltaTime*price)) / (newDeltaTime+oldDeltaTime);
if(newAvgPrice > type(uint128).max){
revert("Overflow");
}
asset[token].avgPrice[index] = uint128(newAvgPrice);
asset[token].timestamp[index] = uint128(block.timestamp);
//Set new index to the next;
asset[token].currentIndex = nextIndex;
}
// This using sliding window oracle of Uniswap V2 data to update this oracle.
function updateAssetPriceFromWindow(address token) external onlyManager{
uint8 index = asset[token].currentIndex;
uint8 lastIndex;
uint8 nextIndex;
ISlidingWindow uniswapOracle = ISlidingWindow(slidingWindow);
if(index == 0){
lastIndex = 5;
} else {
lastIndex = index-1;
}
if(index == 5){
nextIndex = 0;
} else {
nextIndex = index+1;
}
// So.. We helping sliding Window update each time we read parameter.
uniswapOracle.update(token,busd);
uint newDeltaTime = block.timestamp - asset[token].timestamp[lastIndex];
require(newDeltaTime >= periodRange, "update too early"); //If update oracle bot catch this means the privatekey got hacked OR the bot error.
// The price we got already time-weight average price.
uint newAvgPrice = uniswapOracle.consult(token,1e18,busd);
if(newAvgPrice > type(uint128).max){
revert("Overflow");
}
asset[token].avgPrice[index] = uint128(newAvgPrice);
asset[token].timestamp[index] = uint128(block.timestamp);
//Set new index to the next;
asset[token].currentIndex = nextIndex;
}
function updateGoldPrice(uint128 price) external onlyManager {
uint8 index = goldPrice.currentIndex;
uint8 lastIndex;
uint8 nextIndex;
if(index == 0){
lastIndex = 5;
} else {
lastIndex = index-1;
}
uint lastPrice = goldPrice.avgPrice[lastIndex];
if(index == 5){
nextIndex = 0;
} else {
nextIndex = index+1;
}
//newDeltaTime is the time n - time K
//oldDeltaTime is the time K - time 0
uint newDeltaTime = block.timestamp - goldPrice.timestamp[lastIndex];
require(newDeltaTime >= periodRange, "update too early"); //If update oracle bot catch this means the privatekey got hacked OR the bot error.
uint oldDeltaTime = goldPrice.timestamp[lastIndex]-goldPrice.timestamp[nextIndex]; // This need to be initialized
//new AvgPrice is ( price*tk + price*tn ) / tk+tn
uint newAvgPrice = ((oldDeltaTime*lastPrice) + (newDeltaTime*price)) / (newDeltaTime+oldDeltaTime);
if(newAvgPrice > type(uint128).max){
revert("Overflow");
}
//Prevent overvalue / undervalue algorithm, Max change = 10%
if(lastPrice > newAvgPrice) {
//new price is less than previous price
uint dif = lastPrice - newAvgPrice;
if(dif > lastPrice/10){
newAvgPrice = lastPrice * 9 / 10;
}
} else {
//new price is greater than previous price
uint dif = newAvgPrice - lastPrice;
if(dif > lastPrice/10){
newAvgPrice = lastPrice * 11 / 10;
}
}
goldPrice.avgPrice[index] = uint128(newAvgPrice);
goldPrice.timestamp[index] = uint128(block.timestamp);
//Set new index to the next;
goldPrice.currentIndex = nextIndex;
}
function getGoldPrice() external view returns (uint){
uint8 index = goldPrice.currentIndex;
uint8 lastIndex;
if(index == 0){
lastIndex = 5;
} else {
lastIndex = index-1;
}
return uint(goldPrice.avgPrice[lastIndex]);
}
function getUnderlyingPrice(LendTokenInterface lendToken) external view returns (uint){
address underlying;
if(compareStrings(lendToken.symbol(), "lendREI")){
underlying = WREI;
} else {
underlying = lendToken.underlying();
}
//same as assetPrices function
uint8 index = asset[underlying].currentIndex;
uint8 lastIndex;
if(index == 0){
lastIndex = 5;
} else {
lastIndex = index-1;
}
return uint(asset[underlying].avgPrice[lastIndex]);
}
//The latest price is where the lastIndex is.
function assetPrices(address token) external view returns (uint){
uint8 index = asset[token].currentIndex;
uint8 lastIndex;
if(index == 0){
lastIndex = 5;
} else {
lastIndex = index-1;
}
return uint(asset[token].avgPrice[lastIndex]);
}
function compareStrings(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
function _setAdmin (address newAdmin) external onlyAdmin {
address oldAdmin = admin;
admin = newAdmin;
emit SetNewAdmin (oldAdmin, newAdmin);
}
function _setManager (address newManager) external onlyAdmin {
address oldManager = manager;
manager = newManager;
emit SetNewManager(oldManager, newManager);
}
function _setSlidingWindow (address newSlidingWindow) external onlyAdmin {
address oldSlidingWindow = address(slidingWindow);
slidingWindow = ISlidingWindow(newSlidingWindow);
emit SetNewSlidingWindow(oldSlidingWindow, newSlidingWindow);
}
} | Using TWAP model, using index for looping and re-write the price storage | contract AurumOracleCentralized is IAurumOracleCentralized {
pragma solidity 0.8.12;
struct PriceList {
uint128[6] avgPrice;
uint128[6] timestamp;
uint8 currentIndex;
}
mapping (address => bool) alreadyInit;
bool goldInit;
mapping (address => PriceList) asset;
ISlidingWindow public slidingWindow;
function isPriceOracle() external pure returns (bool) {return true;}
constructor (address WREI_, address busd_) {
admin = msg.sender;
busd = busd_;
}
modifier onlyAdmin {
require(msg.sender == admin, "Only admin");
_;
}
modifier onlyManager {
require(msg.sender == manager, "Only manager");
_;
}
error RepeatedInit(address token);
event Initialized_Asset(address token, uint128 price, uint128 timestamp);
event Initialized_Gold(uint128 price, uint128 timestamp);
event SetNewAdmin(address oldAdmin, address newAdmin);
event SetNewManager(address oldManager, address newManager);
event SetNewSlidingWindow(address oldSlidingWindow, address newSlidingWindow);
function initializedAsset(address token, uint128 price) external onlyAdmin{
if(alreadyInit[token]){
revert RepeatedInit(token);
}
uint8 i;
uint128 currentTime = uint128(block.timestamp);
for(i=0;i<6;i++){
asset[token].avgPrice[i] = price;
asset[token].timestamp[i] = currentTime;
}
asset[token].currentIndex = 0;
alreadyInit[token] = true;
emit Initialized_Asset(token, price, currentTime);
}
function initializedAsset(address token, uint128 price) external onlyAdmin{
if(alreadyInit[token]){
revert RepeatedInit(token);
}
uint8 i;
uint128 currentTime = uint128(block.timestamp);
for(i=0;i<6;i++){
asset[token].avgPrice[i] = price;
asset[token].timestamp[i] = currentTime;
}
asset[token].currentIndex = 0;
alreadyInit[token] = true;
emit Initialized_Asset(token, price, currentTime);
}
function initializedAsset(address token, uint128 price) external onlyAdmin{
if(alreadyInit[token]){
revert RepeatedInit(token);
}
uint8 i;
uint128 currentTime = uint128(block.timestamp);
for(i=0;i<6;i++){
asset[token].avgPrice[i] = price;
asset[token].timestamp[i] = currentTime;
}
asset[token].currentIndex = 0;
alreadyInit[token] = true;
emit Initialized_Asset(token, price, currentTime);
}
function initializedGold(uint128 price) external onlyAdmin{
if(goldInit){
revert RepeatedInit(address(0));
}
uint8 i;
uint128 currentTime = uint128(block.timestamp);
for(i=0;i<6;i++){
goldPrice.avgPrice[i] = price;
goldPrice.timestamp[i] = currentTime;
}
goldPrice.currentIndex = 0;
goldInit = true;
emit Initialized_Gold(price, currentTime);
}
function initializedGold(uint128 price) external onlyAdmin{
if(goldInit){
revert RepeatedInit(address(0));
}
uint8 i;
uint128 currentTime = uint128(block.timestamp);
for(i=0;i<6;i++){
goldPrice.avgPrice[i] = price;
goldPrice.timestamp[i] = currentTime;
}
goldPrice.currentIndex = 0;
goldInit = true;
emit Initialized_Gold(price, currentTime);
}
function initializedGold(uint128 price) external onlyAdmin{
if(goldInit){
revert RepeatedInit(address(0));
}
uint8 i;
uint128 currentTime = uint128(block.timestamp);
for(i=0;i<6;i++){
goldPrice.avgPrice[i] = price;
goldPrice.timestamp[i] = currentTime;
}
goldPrice.currentIndex = 0;
goldInit = true;
emit Initialized_Gold(price, currentTime);
}
function updateAssetPrice(address token, uint128 price) external onlyManager{
uint8 index = asset[token].currentIndex;
uint8 lastIndex;
uint8 nextIndex;
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
uint lastPrice = asset[token].avgPrice[lastIndex];
if(index == 5){
nextIndex = 0;
nextIndex = index+1;
}
if(newAvgPrice > type(uint128).max){
revert("Overflow");
}
asset[token].avgPrice[index] = uint128(newAvgPrice);
asset[token].timestamp[index] = uint128(block.timestamp);
}
function updateAssetPrice(address token, uint128 price) external onlyManager{
uint8 index = asset[token].currentIndex;
uint8 lastIndex;
uint8 nextIndex;
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
uint lastPrice = asset[token].avgPrice[lastIndex];
if(index == 5){
nextIndex = 0;
nextIndex = index+1;
}
if(newAvgPrice > type(uint128).max){
revert("Overflow");
}
asset[token].avgPrice[index] = uint128(newAvgPrice);
asset[token].timestamp[index] = uint128(block.timestamp);
}
} else {
function updateAssetPrice(address token, uint128 price) external onlyManager{
uint8 index = asset[token].currentIndex;
uint8 lastIndex;
uint8 nextIndex;
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
uint lastPrice = asset[token].avgPrice[lastIndex];
if(index == 5){
nextIndex = 0;
nextIndex = index+1;
}
if(newAvgPrice > type(uint128).max){
revert("Overflow");
}
asset[token].avgPrice[index] = uint128(newAvgPrice);
asset[token].timestamp[index] = uint128(block.timestamp);
}
} else {
uint newDeltaTime = block.timestamp - asset[token].timestamp[lastIndex];
uint newAvgPrice = ((oldDeltaTime*lastPrice) + (newDeltaTime*price)) / (newDeltaTime+oldDeltaTime);
function updateAssetPrice(address token, uint128 price) external onlyManager{
uint8 index = asset[token].currentIndex;
uint8 lastIndex;
uint8 nextIndex;
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
uint lastPrice = asset[token].avgPrice[lastIndex];
if(index == 5){
nextIndex = 0;
nextIndex = index+1;
}
if(newAvgPrice > type(uint128).max){
revert("Overflow");
}
asset[token].avgPrice[index] = uint128(newAvgPrice);
asset[token].timestamp[index] = uint128(block.timestamp);
}
asset[token].currentIndex = nextIndex;
function updateAssetPriceFromWindow(address token) external onlyManager{
uint8 index = asset[token].currentIndex;
uint8 lastIndex;
uint8 nextIndex;
ISlidingWindow uniswapOracle = ISlidingWindow(slidingWindow);
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
if(index == 5){
nextIndex = 0;
nextIndex = index+1;
}
uint newDeltaTime = block.timestamp - asset[token].timestamp[lastIndex];
if(newAvgPrice > type(uint128).max){
revert("Overflow");
}
asset[token].avgPrice[index] = uint128(newAvgPrice);
asset[token].timestamp[index] = uint128(block.timestamp);
}
function updateAssetPriceFromWindow(address token) external onlyManager{
uint8 index = asset[token].currentIndex;
uint8 lastIndex;
uint8 nextIndex;
ISlidingWindow uniswapOracle = ISlidingWindow(slidingWindow);
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
if(index == 5){
nextIndex = 0;
nextIndex = index+1;
}
uint newDeltaTime = block.timestamp - asset[token].timestamp[lastIndex];
if(newAvgPrice > type(uint128).max){
revert("Overflow");
}
asset[token].avgPrice[index] = uint128(newAvgPrice);
asset[token].timestamp[index] = uint128(block.timestamp);
}
} else {
function updateAssetPriceFromWindow(address token) external onlyManager{
uint8 index = asset[token].currentIndex;
uint8 lastIndex;
uint8 nextIndex;
ISlidingWindow uniswapOracle = ISlidingWindow(slidingWindow);
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
if(index == 5){
nextIndex = 0;
nextIndex = index+1;
}
uint newDeltaTime = block.timestamp - asset[token].timestamp[lastIndex];
if(newAvgPrice > type(uint128).max){
revert("Overflow");
}
asset[token].avgPrice[index] = uint128(newAvgPrice);
asset[token].timestamp[index] = uint128(block.timestamp);
}
} else {
uniswapOracle.update(token,busd);
uint newAvgPrice = uniswapOracle.consult(token,1e18,busd);
function updateAssetPriceFromWindow(address token) external onlyManager{
uint8 index = asset[token].currentIndex;
uint8 lastIndex;
uint8 nextIndex;
ISlidingWindow uniswapOracle = ISlidingWindow(slidingWindow);
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
if(index == 5){
nextIndex = 0;
nextIndex = index+1;
}
uint newDeltaTime = block.timestamp - asset[token].timestamp[lastIndex];
if(newAvgPrice > type(uint128).max){
revert("Overflow");
}
asset[token].avgPrice[index] = uint128(newAvgPrice);
asset[token].timestamp[index] = uint128(block.timestamp);
}
asset[token].currentIndex = nextIndex;
function updateGoldPrice(uint128 price) external onlyManager {
uint8 index = goldPrice.currentIndex;
uint8 lastIndex;
uint8 nextIndex;
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
uint lastPrice = goldPrice.avgPrice[lastIndex];
if(index == 5){
nextIndex = 0;
nextIndex = index+1;
}
if(newAvgPrice > type(uint128).max){
revert("Overflow");
}
if(lastPrice > newAvgPrice) {
uint dif = lastPrice - newAvgPrice;
if(dif > lastPrice/10){
newAvgPrice = lastPrice * 9 / 10;
}
if(dif > lastPrice/10){
newAvgPrice = lastPrice * 11 / 10;
}
}
goldPrice.avgPrice[index] = uint128(newAvgPrice);
goldPrice.timestamp[index] = uint128(block.timestamp);
}
function updateGoldPrice(uint128 price) external onlyManager {
uint8 index = goldPrice.currentIndex;
uint8 lastIndex;
uint8 nextIndex;
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
uint lastPrice = goldPrice.avgPrice[lastIndex];
if(index == 5){
nextIndex = 0;
nextIndex = index+1;
}
if(newAvgPrice > type(uint128).max){
revert("Overflow");
}
if(lastPrice > newAvgPrice) {
uint dif = lastPrice - newAvgPrice;
if(dif > lastPrice/10){
newAvgPrice = lastPrice * 9 / 10;
}
if(dif > lastPrice/10){
newAvgPrice = lastPrice * 11 / 10;
}
}
goldPrice.avgPrice[index] = uint128(newAvgPrice);
goldPrice.timestamp[index] = uint128(block.timestamp);
}
} else {
function updateGoldPrice(uint128 price) external onlyManager {
uint8 index = goldPrice.currentIndex;
uint8 lastIndex;
uint8 nextIndex;
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
uint lastPrice = goldPrice.avgPrice[lastIndex];
if(index == 5){
nextIndex = 0;
nextIndex = index+1;
}
if(newAvgPrice > type(uint128).max){
revert("Overflow");
}
if(lastPrice > newAvgPrice) {
uint dif = lastPrice - newAvgPrice;
if(dif > lastPrice/10){
newAvgPrice = lastPrice * 9 / 10;
}
if(dif > lastPrice/10){
newAvgPrice = lastPrice * 11 / 10;
}
}
goldPrice.avgPrice[index] = uint128(newAvgPrice);
goldPrice.timestamp[index] = uint128(block.timestamp);
}
} else {
uint newDeltaTime = block.timestamp - goldPrice.timestamp[lastIndex];
uint newAvgPrice = ((oldDeltaTime*lastPrice) + (newDeltaTime*price)) / (newDeltaTime+oldDeltaTime);
function updateGoldPrice(uint128 price) external onlyManager {
uint8 index = goldPrice.currentIndex;
uint8 lastIndex;
uint8 nextIndex;
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
uint lastPrice = goldPrice.avgPrice[lastIndex];
if(index == 5){
nextIndex = 0;
nextIndex = index+1;
}
if(newAvgPrice > type(uint128).max){
revert("Overflow");
}
if(lastPrice > newAvgPrice) {
uint dif = lastPrice - newAvgPrice;
if(dif > lastPrice/10){
newAvgPrice = lastPrice * 9 / 10;
}
if(dif > lastPrice/10){
newAvgPrice = lastPrice * 11 / 10;
}
}
goldPrice.avgPrice[index] = uint128(newAvgPrice);
goldPrice.timestamp[index] = uint128(block.timestamp);
}
function updateGoldPrice(uint128 price) external onlyManager {
uint8 index = goldPrice.currentIndex;
uint8 lastIndex;
uint8 nextIndex;
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
uint lastPrice = goldPrice.avgPrice[lastIndex];
if(index == 5){
nextIndex = 0;
nextIndex = index+1;
}
if(newAvgPrice > type(uint128).max){
revert("Overflow");
}
if(lastPrice > newAvgPrice) {
uint dif = lastPrice - newAvgPrice;
if(dif > lastPrice/10){
newAvgPrice = lastPrice * 9 / 10;
}
if(dif > lastPrice/10){
newAvgPrice = lastPrice * 11 / 10;
}
}
goldPrice.avgPrice[index] = uint128(newAvgPrice);
goldPrice.timestamp[index] = uint128(block.timestamp);
}
function updateGoldPrice(uint128 price) external onlyManager {
uint8 index = goldPrice.currentIndex;
uint8 lastIndex;
uint8 nextIndex;
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
uint lastPrice = goldPrice.avgPrice[lastIndex];
if(index == 5){
nextIndex = 0;
nextIndex = index+1;
}
if(newAvgPrice > type(uint128).max){
revert("Overflow");
}
if(lastPrice > newAvgPrice) {
uint dif = lastPrice - newAvgPrice;
if(dif > lastPrice/10){
newAvgPrice = lastPrice * 9 / 10;
}
if(dif > lastPrice/10){
newAvgPrice = lastPrice * 11 / 10;
}
}
goldPrice.avgPrice[index] = uint128(newAvgPrice);
goldPrice.timestamp[index] = uint128(block.timestamp);
}
} else {
uint dif = newAvgPrice - lastPrice;
function updateGoldPrice(uint128 price) external onlyManager {
uint8 index = goldPrice.currentIndex;
uint8 lastIndex;
uint8 nextIndex;
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
uint lastPrice = goldPrice.avgPrice[lastIndex];
if(index == 5){
nextIndex = 0;
nextIndex = index+1;
}
if(newAvgPrice > type(uint128).max){
revert("Overflow");
}
if(lastPrice > newAvgPrice) {
uint dif = lastPrice - newAvgPrice;
if(dif > lastPrice/10){
newAvgPrice = lastPrice * 9 / 10;
}
if(dif > lastPrice/10){
newAvgPrice = lastPrice * 11 / 10;
}
}
goldPrice.avgPrice[index] = uint128(newAvgPrice);
goldPrice.timestamp[index] = uint128(block.timestamp);
}
goldPrice.currentIndex = nextIndex;
function getGoldPrice() external view returns (uint){
uint8 index = goldPrice.currentIndex;
uint8 lastIndex;
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
return uint(goldPrice.avgPrice[lastIndex]);
}
function getGoldPrice() external view returns (uint){
uint8 index = goldPrice.currentIndex;
uint8 lastIndex;
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
return uint(goldPrice.avgPrice[lastIndex]);
}
} else {
function getUnderlyingPrice(LendTokenInterface lendToken) external view returns (uint){
address underlying;
if(compareStrings(lendToken.symbol(), "lendREI")){
underlying = WREI;
underlying = lendToken.underlying();
}
uint8 lastIndex;
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
return uint(asset[underlying].avgPrice[lastIndex]);
}
function getUnderlyingPrice(LendTokenInterface lendToken) external view returns (uint){
address underlying;
if(compareStrings(lendToken.symbol(), "lendREI")){
underlying = WREI;
underlying = lendToken.underlying();
}
uint8 lastIndex;
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
return uint(asset[underlying].avgPrice[lastIndex]);
}
} else {
uint8 index = asset[underlying].currentIndex;
function getUnderlyingPrice(LendTokenInterface lendToken) external view returns (uint){
address underlying;
if(compareStrings(lendToken.symbol(), "lendREI")){
underlying = WREI;
underlying = lendToken.underlying();
}
uint8 lastIndex;
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
return uint(asset[underlying].avgPrice[lastIndex]);
}
} else {
function assetPrices(address token) external view returns (uint){
uint8 index = asset[token].currentIndex;
uint8 lastIndex;
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
return uint(asset[token].avgPrice[lastIndex]);
}
function assetPrices(address token) external view returns (uint){
uint8 index = asset[token].currentIndex;
uint8 lastIndex;
if(index == 0){
lastIndex = 5;
lastIndex = index-1;
}
return uint(asset[token].avgPrice[lastIndex]);
}
} else {
function compareStrings(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
function _setAdmin (address newAdmin) external onlyAdmin {
address oldAdmin = admin;
admin = newAdmin;
emit SetNewAdmin (oldAdmin, newAdmin);
}
function _setManager (address newManager) external onlyAdmin {
address oldManager = manager;
manager = newManager;
emit SetNewManager(oldManager, newManager);
}
function _setSlidingWindow (address newSlidingWindow) external onlyAdmin {
address oldSlidingWindow = address(slidingWindow);
slidingWindow = ISlidingWindow(newSlidingWindow);
emit SetNewSlidingWindow(oldSlidingWindow, newSlidingWindow);
}
} | 955,266 | [
1,
7736,
24722,
2203,
938,
16,
1450,
770,
364,
25004,
471,
283,
17,
2626,
326,
6205,
2502,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
432,
14480,
23601,
39,
12839,
1235,
353,
467,
37,
14480,
23601,
39,
12839,
1235,
288,
203,
203,
377,
203,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
2138,
31,
203,
565,
1958,
20137,
682,
288,
203,
3639,
2254,
10392,
63,
26,
65,
11152,
5147,
31,
203,
3639,
2254,
10392,
63,
26,
65,
2858,
31,
203,
3639,
2254,
28,
17032,
31,
203,
565,
289,
203,
565,
2874,
261,
2867,
516,
1426,
13,
1818,
2570,
31,
203,
565,
1426,
20465,
2570,
31,
203,
377,
203,
565,
2874,
261,
2867,
516,
20137,
682,
13,
3310,
31,
203,
203,
565,
467,
3738,
10415,
3829,
1071,
2020,
10415,
3829,
31,
203,
203,
203,
203,
203,
203,
203,
565,
445,
353,
5147,
23601,
1435,
3903,
16618,
1135,
261,
6430,
13,
288,
2463,
638,
31,
97,
203,
565,
3885,
261,
2867,
678,
862,
45,
67,
16,
1758,
5766,
72,
67,
13,
288,
203,
3639,
3981,
273,
1234,
18,
15330,
31,
203,
3639,
5766,
72,
273,
5766,
72,
67,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
4446,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3981,
16,
315,
3386,
3981,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
565,
9606,
1338,
1318,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3301,
16,
315,
3386,
3301,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
555,
868,
9061,
2570,
12,
2867,
1147,
1769,
203,
203,
565,
871,
10188,
1235,
67,
6672,
12,
2867,
1147,
16,
2254,
10392,
6205,
16,
2254,
10392,
2858,
1769,
203,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
pragma abicoder v2;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {Arrays} from "@openzeppelin/contracts/utils/Arrays.sol";
import {IUZV1Staking} from "./interfaces/IUZV1Staking.sol";
import {IUZV1DAO} from "./interfaces/dao/IUZV1DAO.sol";
import {UZV1ProAccess} from "./membership/UZV1ProAccess.sol";
import {SharedDataTypes} from "./libraries/SharedDataTypes.sol";
/**
* @title UnizenStaking
* @author Unizen
* @notice Unizen staking contract V1 that keeps track of stakes and TVL
**/
contract UZV1Staking is IUZV1Staking, UZV1ProAccess {
using SafeMath for uint256;
/* === STATE VARIABLES === */
// dao contract
IUZV1DAO public dao;
// storage of user stakes
mapping(address => SharedDataTypes.StakerUser) public stakerUsers;
// stakeable tokens data
mapping(address => SharedDataTypes.StakeableToken) public stakeableTokens;
// all whitelisted tokens
address[] public activeTokens;
// zcxht token address
address public zcxht;
// combined weight of all active tokens
// stored to prevent recalculations of the weight
// for every pool update
uint256 public combinedTokenWeight;
function initialize(
address _zcx,
uint256 _zcxTokenWeight,
address _accessToken
) public initializer {
UZV1ProAccess.initialize(_accessToken);
// setup first stakeable token
SharedDataTypes.StakeableToken storage _token = stakeableTokens[_zcx];
// set token data
_token.weight = _zcxTokenWeight;
_token.active = true;
// add token to active list
activeTokens.push(_zcx);
// setup helpers for token weight
combinedTokenWeight = _zcxTokenWeight;
}
/* === VIEW FUNCTIONS === */
/**
* @dev Helper function to get the current TVL
*
* @return array with amounts staked on this contract
**/
function getTVLs() external view override returns (uint256[] memory) {
return getTVLs(block.number);
}
/**
* @dev Helper function to get the TVL on a block.number
*
* @return array with amounts staked on this contract
**/
function getTVLs(uint256 _blocknumber)
public
view
override
returns (uint256[] memory)
{
uint256[] memory _tvl = new uint256[](activeTokens.length);
for (uint8 i = 0; i < activeTokens.length; i++) {
_tvl[i] = _getTVL(_blocknumber, activeTokens[i]);
}
return _tvl;
}
function _getTVL(uint256 _blocknumber, address _token)
internal
view
returns (uint256)
{
uint256 _tvl;
if (_blocknumber == block.number) {
// if blocknumber is current block number, we return the last saved TVL
_tvl = stakeableTokens[_token].totalValueLocked;
} else {
_tvl = stakeableTokens[_token].totalValueLockedSnapshots[
_blocknumber
];
// if we don't find a TVL snapshot, we search in the snapshot array
if (_tvl == 0) {
(uint256 _lastSavedBlock, ) = _findLastSavedBlock(
stakeableTokens[_token].totalValueLockedKeys,
_blocknumber
);
if (_lastSavedBlock == 0) {
_tvl = 0;
} else {
_tvl = stakeableTokens[_token].totalValueLockedSnapshots[
_lastSavedBlock
];
}
}
}
return _tvl;
}
/**
* @dev used to calculate the users stake of the pool
* @param _user optional user addres, if empty the sender will be used
* @param _precision optional denominator, default to 3
*
* @return array with the percentage stakes of the user based on TVL of each allowed token
* [
* weightedAverage,
* shareOfUtilityToken,
* ShareOfLPToken...
* ]
*
**/
function getUserTVLShare(address _user, uint256 _precision)
external
view
override
returns (uint256[] memory)
{
// precision is 3 by default
if (_precision == 0) {
_precision = 3;
}
// default to sender if no user is specified
if (_user == address(0)) {
_user = _msgSender();
}
uint256 _denominator = 10**(_precision.add(2));
// for precision rounding
_denominator = _denominator.mul(10);
uint256[] memory _shares = new uint256[](activeTokens.length + 1);
uint256 _sumWeight = 0;
uint256 _sumShares = 0;
for (uint256 i = 0; i < activeTokens.length; i++) {
// calculate users percentage stakes
uint256 _tokenShare;
if (stakeableTokens[activeTokens[i]].totalValueLocked > 0) {
_tokenShare = stakerUsers[_user]
.stakedAmount[activeTokens[i]]
.mul(_denominator)
.div(stakeableTokens[activeTokens[i]].totalValueLocked);
}
// check current weight of token
uint256 _tokenWeight = stakeableTokens[activeTokens[i]].weight;
// add current token weight to weight sum
_sumWeight = _sumWeight.add(_tokenWeight);
// add users current token share to share sum
_sumShares = _sumShares.add(_tokenShare.mul(_tokenWeight));
// add users percentage stakes of current token, including precision rounding
_shares[i + 1] = _tokenShare.add(5).div(10);
}
// calculate final weighted average of user stakes
_shares[0] = _sumShares.div(_sumWeight).add(5).div(10);
return _shares;
}
/**
* @dev Helper function to get the staked token amount
*
* @return uint256 staked amount of token
**/
function getUsersStakedAmountOfToken(address _user, address _token)
external
view
override
returns (uint256)
{
if (_token == zcxht) {
return stakerUsers[_user].zcxhtStakedAmount;
} else {
return stakerUsers[_user].stakedAmount[_token];
}
}
/**
* @dev Helper function to fetch all existing data to an address
*
* @return array of token addresses
* @return array of users staked amount for each token
* @return ZCXHT staked amount
**/
function getUserData(address _user)
external
view
override
returns (
address[] memory,
uint256[] memory,
uint256
)
{
// init temporary array with token count
uint256[] memory _userStakes = new uint256[](activeTokens.length);
// loop through all known tokens
for (uint8 i = 0; i < activeTokens.length; i++) {
// get user stakes for active token
_userStakes[i] = stakerUsers[_user].stakedAmount[activeTokens[i]];
}
// return active token stakes
return (
activeTokens,
_userStakes,
stakerUsers[_user].zcxhtStakedAmount
);
}
/**
* @dev Creates a list of active tokens, excluding inactive tokens
*
* @return address[] array of active stakeable token tokens
**/
function getActiveTokens() public view override returns (address[] memory) {
return activeTokens;
}
/**
* @dev Creates a list of active token weights, excluding inactive tokens
*
* @return weights uint256[] array including every active token weight
* @return combinedWeight uint256 combined weight of all active tokens
**/
function getTokenWeights()
external
view
override
returns (uint256[] memory weights, uint256 combinedWeight)
{
// create new memory array at the size of the current token count
weights = new uint256[](activeTokens.length);
combinedWeight = combinedTokenWeight;
// loop through maximum amount of allowed tokens
for (uint8 i = 0; i < activeTokens.length; i++) {
// add token to active token list
weights[i] = stakeableTokens[activeTokens[i]].weight;
}
}
/**
* @dev Returns all block number snapshots for an specific user and token
*
* @param _user Address of the user
* @param _token Address of the token
* @param _startBlock Start block to search for snapshots
* @param _endBlock End block to search for snapshots
* @param _claimedBlocks Array of block numbers when the user has claimed
*
* @return snapshots snapshoted data grouped by stakes
**/
function getUserStakesSnapshots(
address _user,
address _token,
uint256 _startBlock,
uint256 _endBlock,
uint256[] memory _claimedBlocks
)
external
view
override
returns (SharedDataTypes.StakeSnapshot[] memory snapshots)
{
(, uint256 _index) = _findLastSavedBlock(
stakerUsers[_user].stakedAmountKeys[_token],
_startBlock
);
// read how many snapshots fits in the current startBlock-endBlok period
uint256 numSnapshots;
for (
uint256 i = _index;
i < stakerUsers[_user].stakedAmountKeys[_token].length &&
stakerUsers[_user].stakedAmountKeys[_token][i] <= _endBlock;
i++
) {
numSnapshots++;
}
for (uint256 i = 0; i < _claimedBlocks.length; i++) {
// If the claimed block is inside the period to be calculated...
if (_claimedBlocks[i] <= _endBlock) {
numSnapshots++;
}
}
// create the snapshot array
SharedDataTypes.StakeSnapshot[]
memory _snapshot = new SharedDataTypes.StakeSnapshot[](
numSnapshots
);
// Add bookmarks for every tranche
uint256 _iStaked = _index;
uint256 _iClaimed = 0;
for (uint256 i = 0; i < _snapshot.length; i++) {
// calculate start block from stakes
uint256 _snapshotStakedBlock = (_iStaked <
stakerUsers[_user].stakedAmountKeys[_token].length &&
stakerUsers[_user].stakedAmountKeys[_token][_iStaked] <=
_endBlock)
? stakerUsers[_user].stakedAmountKeys[_token][_iStaked]
: 0;
uint256 _startSnapshotBlock = (_snapshotStakedBlock > 0 &&
_snapshotStakedBlock < _startBlock)
? _startBlock
: _snapshotStakedBlock;
// calculate start block from claims
uint256 _claimedBlock = (_iClaimed < _claimedBlocks.length)
? _claimedBlocks[_iClaimed]
: 0;
if (
(_startSnapshotBlock != 0 &&
_startSnapshotBlock <= _claimedBlock) || _claimedBlock == 0
) {
_snapshot[i].startBlock = _startSnapshotBlock;
_iStaked = _iStaked.add(1);
} else {
_snapshot[i].startBlock = _claimedBlock;
_iClaimed = _iClaimed.add(1);
}
}
// repeat the iteration to calculate endBlock and tokenTVL
for (uint256 i = 0; i < _snapshot.length; i++) {
// If this is the last snapshoted block, we get the last reward
// block. Else, we get the next initial block minus 1
_snapshot[i].endBlock = (i == numSnapshots.sub(1))
? _endBlock
: _snapshot[i.add(1)].startBlock.sub(1);
// read staked amount
_snapshot[i].stakedAmount = _getUserStakeForToken(
_user,
_token,
_snapshot[i].startBlock
);
// We read the token TVL at first and last block of this snapshot
_snapshot[i].startTVL = _getTVL(_snapshot[i].startBlock, _token);
_snapshot[i].endTVL = _getTVL(_snapshot[i].endBlock, _token);
}
return _snapshot;
}
/**
* @dev Helper function to get the current staked tokens of a user
*
* @return uint256[] array with amounts for every stakeable token
**/
function getUserStakes(address _user)
external
view
override
returns (uint256[] memory)
{
return getUserStakes(_user, block.number);
}
/**
* @dev Helper function to get the staked tokens of a user on a block.number
*
* @return uint256[] array with amounts for every stakeable token
**/
function getUserStakes(address _user, uint256 _blocknumber)
public
view
override
returns (uint256[] memory)
{
// create in memory array with the size of existing active tokens
uint256[] memory _userStakes = new uint256[](activeTokens.length);
// loop through active tokens
for (uint8 i = 0; i < activeTokens.length; i++) {
// get user stakes for active token
_userStakes[i] = _getUserStakeForToken(
_user,
activeTokens[i],
_blocknumber
);
}
// return the data
return _userStakes;
}
/**
* @dev Get the staked amount of a certain token on a block.number
*
* @return _stakedAmount amount of staked amount
**/
function _getUserStakeForToken(
address _user,
address _token,
uint256 _blocknumber
) internal view returns (uint256) {
uint256 _stakedAmount;
if (_blocknumber == block.number) {
// if blocknumber is current block number, we return the last saved staked amount
_stakedAmount = stakerUsers[_user].stakedAmount[_token];
} else {
_stakedAmount = stakerUsers[_user].stakedAmountSnapshots[_token][
_blocknumber
];
// if we don't find a staked amount snapshot, we search in the snapshot array
if (_stakedAmount == 0) {
(uint256 _lastSavedBlock, ) = _findLastSavedBlock(
stakerUsers[_user].stakedAmountKeys[_token],
_blocknumber
);
if (_lastSavedBlock == 0) {
_stakedAmount = 0;
} else {
_stakedAmount = stakerUsers[_user].stakedAmountSnapshots[
_token
][_lastSavedBlock];
}
}
}
return _stakedAmount;
}
/* === MUTATING FUNCTIONS === */
/**
* @dev Convenience function to stake zcx token
* @param _amount Amount of tokens the user wants to stake
*
* @return the new amount of tokens staked
**/
function stake(uint256 _amount)
external
override
whenNotPaused
returns (uint256)
{
return _stake(activeTokens[0], _amount);
}
/**
* @dev Convenience function to stake lp token
* @param _lpToken Address of token to stake
* @param _amount Amount of tokens the user wants to stake
*
* @return the new amount of tokens staked
**/
function stake(address _lpToken, uint256 _amount)
external
override
whenNotPaused
returns (uint256)
{
return _stake(_lpToken, _amount);
}
/**
* @dev This allows users to actually add tokens to the staking pool
* and take part
* @param _token Address of token to stake
* @param _amount Amount of tokens the user wants to stake
*
* @return the new amount of tokens staked
**/
function _stake(address _token, uint256 _amount)
internal
returns (uint256)
{
require(isAllowedToken(_token), "INVALID_TOKEN");
// transfer tokens
SafeERC20.safeTransferFrom(
IERC20(_token),
_msgSender(),
address(this),
_amount
);
address _stakeToken = (_token == zcxht) ? activeTokens[0] : _token; // if stake zcxht, equal to stake zcx
// get current user data
SharedDataTypes.StakerUser storage _stakerUser = stakerUsers[
_msgSender()
];
// calculate new amount of user stakes
uint256 _newStakedAmount = _stakerUser.stakedAmount[_stakeToken].add(
_amount
);
uint256 _newTVL = stakeableTokens[_stakeToken].totalValueLocked.add(
_amount
);
// check if holder token is staked
if (_token == zcxht) {
_stakerUser.zcxhtStakedAmount = _stakerUser.zcxhtStakedAmount.add(
_amount
);
}
_saveStakeInformation(
_msgSender(),
_stakeToken,
_newStakedAmount,
_newTVL
);
// shoot event
emit TVLChange(_msgSender(), _stakeToken, _amount, true);
// return users new holdings of token
return _stakerUser.stakedAmount[_stakeToken];
}
/**
* @dev Convenience function to withdraw utility token
* @param _amount optional value, if empty the total user stake will be used
**/
function withdraw(uint256 _amount)
external
override
whenNotPaused
returns (uint256)
{
return _withdraw(activeTokens[0], _amount);
}
/**
* @dev Convenience function to withdraw LP tokens
* @param _lpToken Address of token to withdraw
* @param _amount optional value, if empty the total user stake will be used
**/
function withdraw(address _lpToken, uint256 _amount)
external
override
whenNotPaused
returns (uint256)
{
return _withdraw(_lpToken, _amount);
}
/**
* @dev This allows users to unstake their tokens at any point of time
* and also leaves it open to the users how much will be unstaked
* @param _token Address of token to withdraw
* @param _amount optional value, if empty the total user stake will be used
**/
function _withdraw(address _token, uint256 _amount)
internal
returns (uint256)
{
require(_amount > 0, "CAN_NOT_WITHDRAW_ZERO");
SharedDataTypes.StakerUser storage _stakerUser = stakerUsers[
_msgSender()
];
address _stakeToken = _token;
uint256 _maxWithdrawable;
if (_stakeToken == zcxht) {
_stakeToken = activeTokens[0];
_maxWithdrawable = _stakerUser.zcxhtStakedAmount;
} else if (_stakeToken == activeTokens[0]) {
_maxWithdrawable = _stakerUser.stakedAmount[_stakeToken].sub(
_stakerUser.zcxhtStakedAmount
);
} else {
_maxWithdrawable = _stakerUser.stakedAmount[_stakeToken];
}
require(_maxWithdrawable >= _amount, "AMOUNT_EXCEEDS_STAKED_BALANCE");
SafeERC20.safeTransfer(IERC20(_token), _msgSender(), _amount); // calculate the new user stakes of the token
uint256 _newStakedAmount = _stakerUser.stakedAmount[_stakeToken].sub(
_amount
);
uint256 _newTVL = stakeableTokens[_stakeToken].totalValueLocked.sub(
_amount
);
// DAO check, if available. Only applies to utility token withdrawals
if (address(dao) != address(0) && _stakeToken == activeTokens[0]) {
// get locked tokens of user (active votes)
uint256 _lockedTokens = dao.getLockedTokenCount(_msgSender());
// check that the user has enough unlocked tokens
require(
_stakerUser.stakedAmount[_stakeToken] >= _lockedTokens,
"DAO_ALL_TOKENS_LOCKED"
);
require(
_stakerUser.stakedAmount[_stakeToken].sub(_lockedTokens) >=
_amount,
"DAO_TOKENS_LOCKED"
);
}
_saveStakeInformation(
_msgSender(),
_stakeToken,
_newStakedAmount,
_newTVL
);
// check if holder token is withdrawn
if (_token == zcxht) {
_stakerUser.zcxhtStakedAmount = _stakerUser.zcxhtStakedAmount.sub(
_amount
);
}
// shoot event
emit TVLChange(_msgSender(), _stakeToken, _amount, false);
return _stakerUser.stakedAmount[_stakeToken];
}
/**
* @dev Checks if the token is whitelisted and active
* @param _token address of token to check
* @return bool Active status of checked token
**/
function isAllowedToken(address _token) public view returns (bool) {
if (_token == address(0)) return false;
return stakeableTokens[_token].active || _token == zcxht;
}
/**
* @dev Allows updating the utility token address that can be staked, in case
* of a token swap or similar event.
* @param _token Address of new ERC20 token address
**/
function updateStakeToken(address _token) external onlyOwner {
require(activeTokens[0] != _token, "SAME_ADDRESS");
// deactive the old token
stakeableTokens[activeTokens[0]].active = false;
// cache the old weight
uint256 weight = stakeableTokens[activeTokens[0]].weight;
// assign the new address
activeTokens[0] = _token;
// update new token data with old settings
stakeableTokens[activeTokens[0]].weight = weight;
stakeableTokens[activeTokens[0]].active = true;
}
/**
* @dev Adds new token to whitelist
* @param _token Address of new token
* @param _weight Weight of new token
**/
function addToken(address _token, uint256 _weight) external onlyOwner {
require(_token != address(0), "ZERO_ADDRESS");
require(isAllowedToken(_token) == false, "EXISTS_ALREADY");
// add token address to active token list
activeTokens.push(_token);
// set token weight
stakeableTokens[_token].weight = _weight;
// set token active
stakeableTokens[_token].active = true;
// add token weight to maximum weight helper
combinedTokenWeight = combinedTokenWeight.add(_weight);
}
/**
* @dev Removes token from whitelist, if no tokens are locked
* @param _token Address of token to remove
**/
function removeToken(address _token) external onlyOwner {
require(isAllowedToken(_token) == true, "INVALID_TOKEN");
require(stakeableTokens[_token].active, "INVALID_TOKEN");
// get token index
uint256 _idx;
for (uint256 i = 0; i < activeTokens.length; i++) {
if (activeTokens[i] == _token) {
_idx = i;
}
}
// remove token weight from maximum weight helper
combinedTokenWeight = combinedTokenWeight.sub(
stakeableTokens[_token].weight
);
// reset token weight
stakeableTokens[_token].weight = 0;
// remove from active tokens list
activeTokens[_idx] = activeTokens[activeTokens.length - 1];
activeTokens.pop();
// set token inactive
stakeableTokens[_token].active = false;
}
function setHolderToken(address _zcxht) external onlyOwner {
require(zcxht != _zcxht, "SAME_ADDRESS");
zcxht = _zcxht;
}
/**
* @dev Allows to update the weight of a specific token
* @param _token Address of the token
* @param _newWeight new token weight
**/
function updateTokenWeight(address _token, uint256 _newWeight)
external
onlyOwner
{
require(_token != address(0), "ZERO_ADDRESS");
require(_newWeight > 0, "NO_TOKEN_WEIGHT");
// update token weight
combinedTokenWeight = combinedTokenWeight
.sub(stakeableTokens[_token].weight)
.add(_newWeight);
stakeableTokens[_token].weight = _newWeight;
}
/**
* @dev Allows updating the dao address, in case of an upgrade.
* @param _newDAO Address of the new Unizen DAO contract
**/
function updateDAO(address _newDAO) external onlyOwner {
require(address(dao) != _newDAO, "SAME_ADDRESS");
dao = IUZV1DAO(_newDAO);
}
/* === INTERNAL FUNCTIONS === */
/**
* @dev Save staking information after stake or withdraw and make an
* sanapshot
*
* @param _user user that makes the stake/withdraw
* @param _token token where the stake/withdraw has been made
* @param _newStakedAmount staked/withdrawn amount of tokens
* @param _newTVL TVL of the token after the stake/withdraw
*/
function _saveStakeInformation(
address _user,
address _token,
uint256 _newStakedAmount,
uint256 _newTVL
) internal {
SharedDataTypes.StakerUser storage _stakerUser = stakerUsers[_user];
// updated total stake of current user
_stakerUser.stakedAmountSnapshots[_token][
block.number
] = _newStakedAmount;
if (
(_stakerUser.stakedAmountKeys[_token].length == 0) ||
_stakerUser.stakedAmountKeys[_token][
_stakerUser.stakedAmountKeys[_token].length - 1
] !=
block.number
) {
_stakerUser.stakedAmountKeys[_token].push(block.number);
}
_stakerUser.stakedAmount[_token] = _newStakedAmount;
// update tvl of token
stakeableTokens[_token].totalValueLockedSnapshots[
block.number
] = _newTVL;
if (
(stakeableTokens[_token].totalValueLockedKeys.length == 0) ||
stakeableTokens[_token].totalValueLockedKeys[
stakeableTokens[_token].totalValueLockedKeys.length - 1
] !=
block.number
) {
stakeableTokens[_token].totalValueLockedKeys.push(block.number);
}
stakeableTokens[_token].totalValueLocked = _newTVL;
}
/**
* @dev Helper function to get the last saved block number in a block index array
*
* @return lastSavedBlock last block number stored in the block index array
* @return index index of the last block number stored in the block index array
**/
function _findLastSavedBlock(
uint256[] storage _blockKeys,
uint256 _blockNumber
) internal view returns (uint256 lastSavedBlock, uint256 index) {
uint256 _upperBound = Arrays.findUpperBound(
_blockKeys,
_blockNumber.add(1)
);
if (_upperBound == 0) {
return (0, 0);
} else {
return (_blockKeys[_upperBound - 1], _upperBound - 1);
}
}
/* === EVENTS === */
event TVLChange(
address indexed user,
address indexed token,
uint256 amount,
bool indexed changeType
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// 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/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
pragma abicoder v2;
import {SharedDataTypes} from "../libraries/SharedDataTypes.sol";
interface IUZV1Staking {
/* view functions */
function getTVLs() external view returns (uint256[] memory);
function getTVLs(uint256 _blocknumber)
external
view
returns (uint256[] memory);
function getUserTVLShare(address _user, uint256 _precision)
external
view
returns (uint256[] memory);
function getUsersStakedAmountOfToken(address _user, address _token)
external
view
returns (uint256);
function getUserData(address _user)
external
view
returns (
address[] memory,
uint256[] memory,
uint256
);
function getActiveTokens() external view returns (address[] memory);
function getTokenWeights()
external
view
returns (uint256[] memory weights, uint256 combinedWeight);
function getUserStakesSnapshots(
address _user,
address _token,
uint256 _startBlock,
uint256 _endBlock,
uint256[] memory _claimedBlocks
) external view returns (SharedDataTypes.StakeSnapshot[] memory snapshots);
function getUserStakes(address _user)
external
view
returns (uint256[] memory);
function getUserStakes(address _user, uint256 _blocknumber)
external
view
returns (uint256[] memory);
/* mutating functions */
function stake(uint256 _amount) external returns (uint256);
function stake(address _lpToken, uint256 _amount)
external
returns (uint256);
function withdraw(uint256 _amount) external returns (uint256);
function withdraw(address _lpToken, uint256 _amount)
external
returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
interface IUZV1DAO {
/* view functions */
function getLockedTokenCount(address _user) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
pragma abicoder v2;
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
/**
* @title UZProAccess
* @author Unizen
* @notice Simple abstract class to add easy checks
* for pro membership access token
**/
abstract contract UZV1ProAccess is
Initializable,
OwnableUpgradeable,
PausableUpgradeable
{
// internal storage of the erc721 token
IERC721 internal _membershipToken;
function initialize(address _token) public virtual initializer {
__Ownable_init();
__Pausable_init();
_setMembershipToken(_token);
}
function membershipToken() public view returns (address) {
return address(_membershipToken);
}
/* === CONTROL FUNCTIONS === */
/**
* @dev pause smart contract
*/
function pause() public onlyOwner {
_pause();
}
/**
* @dev unpause smart contract
*/
function unPause() public onlyOwner {
_unpause();
}
/**
* @dev Allows the owner of the contract, to update
* the used membership token
* @param _newToken address of the new erc721 token
**/
function setMembershipToken(address _newToken) public onlyOwner {
_setMembershipToken(_newToken);
}
function _setMembershipToken(address _newToken) internal {
if (_newToken == address(0) && address(_membershipToken) == address(0))
return;
require(_newToken != address(_membershipToken), "SAME_ADDRESS");
_membershipToken = IERC721(_newToken);
}
/**
* @dev Internal function that checks if the users has any
* membership tokens. Reverts, if none is found.
* @param _user address of user to check
**/
function _checkPro(address _user) internal view {
if (address(_membershipToken) != address(0)) {
require(
_membershipToken.balanceOf(_user) > 0,
"FORBIDDEN: PRO_MEMBER"
);
}
}
/* === MODIFIERS === */
modifier onlyPro(address _user) {
_checkPro(_user);
_;
}
/* === EVENTS === */
event MembershipTokenUpdated(address _newTokenAddress);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
library SharedDataTypes {
// struct for returning snapshot values
struct StakeSnapshot {
// initial block number snapshoted
uint256 startBlock;
// end block number snapshoted
uint256 endBlock;
// staked amount at initial block
uint256 stakedAmount;
// total value locked at start block
uint256 startTVL;
// total value locked at end block
uint256 endTVL;
}
// general staker user information
struct StakerUser {
// snapshotted stakes of the user per token (token => block.number => stakedAmount)
mapping(address => mapping(uint256 => uint256)) stakedAmountSnapshots;
// snapshotted stakes of the user per token keys (token => block.number[])
mapping(address => uint256[]) stakedAmountKeys;
// current stakes of the user per token
mapping(address => uint256) stakedAmount;
// total amount of holder tokens
uint256 zcxhtStakedAmount;
}
// information for stakeable tokens
struct StakeableToken {
// snapshotted total value locked (TVL) (block.number => totalValueLocked)
mapping(uint256 => uint256) totalValueLockedSnapshots;
// snapshotted total value locked (TVL) keys (block.number[])
uint256[] totalValueLockedKeys;
// current total value locked (TVL)
uint256 totalValueLocked;
uint256 weight;
bool active;
}
// POOL DATA
// data object for a user stake on a pool
struct PoolStakerUser {
// saved / withdrawn rewards of user
uint256 totalSavedRewards;
// total purchased allocation
uint256 totalPurchasedAllocation;
// native address, if necessary
string nativeAddress;
// date/time when user has claimed (paid in incubator pools) the reward
uint256 claimedTime;
// blocks where the user has claimed the rewards
uint256[] claimedBlocks;
}
// flat data type of stake for UI
struct FlatPoolStakerUser {
address[] tokens;
uint256[] amounts;
uint256 pendingRewards;
uint256 totalPurchasedAllocation;
uint256 totalSavedRewards;
uint256 claimedTime;
PoolState state;
UserPoolState userState;
}
// UI information for pool
// data will be fetched via github token repository
// blockchain / cAddress being the most relevant values
// for fetching the correct token data
struct PoolInfo {
// token name
string name;
// name of blockchain, as written on github
string blockchain;
// tokens contract address on chain
string cAddress;
}
// possible states of the reward pool
enum PoolState {
pendingStaking,
staking,
pendingPayment,
payment,
pendingDistribution,
distribution,
retired
}
// possible states of the reward pool's user
enum UserPoolState {
notclaimed,
claimed,
rejected,
missed
}
// input data for new reward pools
struct PoolInputData {
// total rewards to distribute
uint256 totalRewards;
// start block for distribution
uint256 startBlock;
// end block for distribution
uint256 endBlock;
// erc token address
address token;
// pool type
uint8 poolType;
// information about the reward token
PoolInfo tokenInfo;
}
struct PoolData {
PoolState state;
// pool information for the ui
PoolInfo info;
// start block of staking rewards
uint256 startBlock;
// end block of staking rewards
uint256 endBlock;
// start block of payment period
uint256 paymentStartBlock;
// end block of payment period
uint256 paymentEndBlock;
// start block of distribution period
uint256 distributionStartBlock;
// end block of distribution period
uint256 distributionEndBlock;
// total rewards for allocation
uint256 totalRewards;
// rewards per block
uint256 rewardsPerBlock;
// price of a single payment token
uint256 rewardTokenPrice;
// type of the pool
uint8 poolType;
// address of payment token
address paymentToken;
// address of reward token
address token;
// total remaining rewards for allocation (claimed or not claimed)
// uint256 remainingRewards;
// total open rewards for allocation (rewards not claimed)
// uint256 openRewards;
}
}
// 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 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.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
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.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 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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/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.
*/
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;
} | data object for a user stake on a pool saved / withdrawn rewards of user total purchased allocation native address, if necessary date/time when user has claimed (paid in incubator pools) the reward blocks where the user has claimed the rewards | struct PoolStakerUser {
uint256 totalSavedRewards;
uint256 totalPurchasedAllocation;
string nativeAddress;
uint256 claimedTime;
uint256[] claimedBlocks;
}
| 10,367,207 | [
1,
892,
733,
364,
279,
729,
384,
911,
603,
279,
2845,
5198,
342,
598,
9446,
82,
283,
6397,
434,
729,
2078,
5405,
343,
8905,
13481,
6448,
1758,
16,
309,
4573,
1509,
19,
957,
1347,
729,
711,
7516,
329,
261,
29434,
316,
7290,
373,
639,
16000,
13,
326,
19890,
4398,
1625,
326,
729,
711,
7516,
329,
326,
283,
6397,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1958,
8828,
510,
6388,
1299,
288,
203,
3639,
2254,
5034,
2078,
16776,
17631,
14727,
31,
203,
3639,
2254,
5034,
2078,
10262,
343,
8905,
17353,
31,
203,
3639,
533,
6448,
1887,
31,
203,
3639,
2254,
5034,
7516,
329,
950,
31,
203,
3639,
2254,
5034,
8526,
7516,
329,
6450,
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.0;
pragma experimental ABIEncoderV2;
library ECStructs {
struct ECDSASig {
uint8 v;
bytes32 r;
bytes32 s;
}
}
contract ILotteryForCoke {
struct Ticket {
address payable ticketAddress;
uint256 period;
address payable buyer;
uint256 amount;
uint256 salt;
}
function buy(Ticket memory ticket, ECStructs.ECDSASig memory serverSig) public returns (bool);
function calcTicketPrice(Ticket memory ticket) public view returns (uint256 cokeAmount);
}
contract IPledgeForCoke {
struct DepositRequest {
address payable depositAddress;
address payable from;
uint256 cokeAmount;
uint256 endBlock;
bytes32 billSeq;
bytes32 salt;
}
//the buyer should approve enough coke and then call this function
//or use 'approveAndCall' in Coke.sol in 1 request
function deposit(DepositRequest memory request, ECStructs.ECDSASig memory ecdsaSig) payable public returns (bool);
function depositCheck(DepositRequest memory request, ECStructs.ECDSASig memory ecdsaSig) public view returns (uint256);
}
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, "SafeMath, mul");
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, "SafeMath, div");
// 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, "SafeMath, sub");
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, "SafeMath, add");
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, "SafeMath, mod");
return a % b;
}
}
contract IRequireUtils {
function requireCode(uint256 code) external pure;
function interpret(uint256 code) public pure returns (string memory);
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor() internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @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() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "nonReentrant");
}
}
contract ERC20 is IERC20, ReentrancyGuard {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0), "ERC20 approve, spender can not be 0x00");
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
//be careful, this is 'internal' function,
//you must add control permission to manipulate this function
function approveFrom(address owner, address spender, uint256 value) internal returns (bool) {
require(spender != address(0), "ERC20 approveFrom, spender can not be 0x00");
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender], "ERC20 transferFrom, allowance not enough");
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0), "ERC20 increaseAllowance, spender can not be 0x00");
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0), "ERC20 decreaseAllowance, spender can not be 0x00");
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from], "ERC20 _transfer, not enough balance");
require(to != address(0), "ERC20 _transfer, to address can not be 0x00");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0), "ERC20 _mint, account can not be 0x00");
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0), "ERC20 _burn, account can not be 0x00");
require(value <= _balances[account], "ERC20 _burn, not enough balance");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender], "ERC20 _burnFrom, allowance not enough");
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
contract Coke is ERC20{
using SafeMath for uint256;
IRequireUtils rUtils;
//1 Coke = 10^18 Tin
string public name = "COKE";
string public symbol = "COKE";
uint256 public decimals = 18; //1:1
address public cokeAdmin;// admin has rights to mint and burn and etc.
mapping(address => bool) public gameMachineRecords;// game machine has permission to mint coke
uint256 public stagePercent;
uint256 public step;
uint256 public remain;
uint256 public currentDifficulty;//starts from 0
uint256 public currentStageEnd;
address team;
uint256 public teamRemain;
uint256 public unlockAllBlockNumber;
uint256 unlockNumerator;
uint256 unlockDenominator;
event Reward(address indexed account, uint256 amount, uint256 rawAmount);
event UnlockToTeam(address indexed account, uint256 amount, uint256 rawReward);
constructor (IRequireUtils _rUtils, address _cokeAdmin, uint256 _cap, address _team, uint256 _toTeam,
uint256 _unlockAllBlockNumber, address _bounty, uint256 _toBounty, uint256 _stagePercent,
uint256 _unlockNumerator, uint256 _unlockDenominator) /*ERC20Capped(_cap) */public {
rUtils = _rUtils;
cokeAdmin = _cokeAdmin;
unlockAllBlockNumber = _unlockAllBlockNumber;
team = _team;
teamRemain = _toTeam;
_mint(address(this), _toTeam);
_mint(_bounty, _toBounty);
stagePercent = _stagePercent;
step = _cap * _stagePercent / 100;
remain = _cap.sub(_toTeam).sub(_toBounty);
_mint(address(this), remain);
unlockNumerator = _unlockNumerator;
unlockDenominator=_unlockDenominator;
if (remain - step > 0) {
currentStageEnd = remain - step;
} else {
currentStageEnd = 0;
}
currentDifficulty = 0;
}
function approveAndCall(address spender, uint256 value, bytes memory data) public nonReentrant returns (bool) {
require(approve(spender, value));
(bool success, bytes memory returnData) = spender.call(data);
rUtils.requireCode(success ? 0 : 501);
return true;
}
function approveAndBuyLottery(ILotteryForCoke.Ticket memory ticket, ECStructs.ECDSASig memory serverSig) public nonReentrant returns (bool){
rUtils.requireCode(approve(ticket.ticketAddress, ILotteryForCoke(ticket.ticketAddress).calcTicketPrice(ticket)) ? 0 : 506);
rUtils.requireCode(ILotteryForCoke(ticket.ticketAddress).buy(ticket, serverSig) ? 0 : 507);
return true;
}
function approveAndPledgeCoke(IPledgeForCoke.DepositRequest memory depositRequest, ECStructs.ECDSASig memory serverSig) public nonReentrant returns (bool){
rUtils.requireCode(approve(depositRequest.depositAddress, depositRequest.cokeAmount) ? 0 : 508);
rUtils.requireCode(IPledgeForCoke(depositRequest.depositAddress).deposit(depositRequest, serverSig) ? 0 : 509);
return true;
}
function betReward(address _account, uint256 _amount) public mintPermission returns (uint256 minted){
uint256 input = _amount;
uint256 totalMint = 0;
while (input > 0) {
uint256 factor = 2 ** currentDifficulty;
uint256 discount = input / factor;
if (input % factor != 0) {
discount ++;
}
if (discount > remain - currentStageEnd) {
uint256 toMint = remain - currentStageEnd;
totalMint += toMint;
input = input - toMint * factor;
remain = currentStageEnd;
} else {
totalMint += discount;
input = 0;
remain = remain - discount;
}
//update to next stage
if (remain == currentStageEnd) {
if (currentStageEnd != 0) {
currentDifficulty = currentDifficulty + 1;
if (remain - step > 0) {
currentStageEnd = remain - step;
} else {
currentStageEnd = 0;
}
} else {
input = 0;
}
}
}
_transfer(address(this), _account, totalMint);
emit Reward(_account, totalMint, _amount);
uint256 mintToTeam = totalMint * unlockDenominator / unlockNumerator;
if (teamRemain >= mintToTeam) {
teamRemain = teamRemain - mintToTeam;
_transfer(address(this), team, mintToTeam);
emit UnlockToTeam(team, mintToTeam, totalMint);
}
return totalMint;
}
function setGameMachineRecords(address _input, bool _isActivated) public onlyCokeAdmin {
gameMachineRecords[_input] = _isActivated;
}
function unlockAllTeamCoke() public onlyCokeAdmin {
if (block.number > unlockAllBlockNumber) {
_transfer(address(this), team, teamRemain);
teamRemain = 0;
emit UnlockToTeam(team, teamRemain, 0);
}
}
modifier onlyCokeAdmin(){
rUtils.requireCode(msg.sender == cokeAdmin ? 0 : 503);
_;
}
modifier mintPermission(){
rUtils.requireCode(gameMachineRecords[msg.sender] == true ? 0 : 505);
_;
}
} | * @dev Transfer tokens from one address to another @param from address The address which you want to send tokens from @param to address The address which you want to transfer to @param value uint256 the amount of tokens to be transferred/ | function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender], "ERC20 transferFrom, allowance not enough");
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
| 7,326,957 | [
1,
5912,
2430,
628,
1245,
1758,
358,
4042,
225,
628,
1758,
1021,
1758,
1492,
1846,
2545,
358,
1366,
2430,
628,
225,
358,
1758,
1021,
1758,
1492,
1846,
2545,
358,
7412,
358,
225,
460,
2254,
5034,
326,
3844,
434,
2430,
358,
506,
906,
4193,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
7412,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
460,
203,
565,
262,
203,
565,
1071,
203,
565,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
2583,
12,
1132,
1648,
389,
8151,
63,
2080,
6362,
3576,
18,
15330,
6487,
315,
654,
39,
3462,
7412,
1265,
16,
1699,
1359,
486,
7304,
8863,
203,
203,
3639,
389,
8151,
63,
2080,
6362,
3576,
18,
15330,
65,
273,
389,
8151,
63,
2080,
6362,
3576,
18,
15330,
8009,
1717,
12,
1132,
1769,
203,
3639,
389,
13866,
12,
2080,
16,
358,
16,
460,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// Dependency file: contracts/zeppelin/upgradable/Initializable.sol
// SPDX-License-Identifier: MIT
// pragma solidity ^0.7.0;
// pragma abicoder v2;
/**
* @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 || !initialized, "Contract instance is already initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// Dependency file: contracts/zeppelin/upgradable/utils/ReentrancyGuard.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
// import "contracts/zeppelin/upgradable/Initializable.sol";
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard is Initializable {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
function initialize() public initializer {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @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() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: no reentrant allowed");
}
}
// Dependency file: contracts/zeppelin/GSN/Context.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
/*
* @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 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/zeppelin/access/Roles.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account doesn't have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// Dependency file: contracts/zeppelin/upgradable/access/roles/UpgradablePauserRole.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
// import "contracts/zeppelin/upgradable/Initializable.sol";
// import "contracts/zeppelin/GSN/Context.sol";
// import "contracts/zeppelin/access/Roles.sol";
contract UpgradablePauserRole is Initializable, Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
function __PauserRol_init(address sender) public initializer {
if (!isPauser(sender)) {
_addPauser(sender);
}
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller doesn't have the role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
// Dependency file: contracts/zeppelin/upgradable/lifecycle/UpgradablePausable.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
// import "contracts/zeppelin/upgradable/Initializable.sol";
// import "contracts/zeppelin/GSN/Context.sol";
// import "contracts/zeppelin/upgradable/access/roles/UpgradablePauserRole.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 UpgradablePausable is Initializable, Context, UpgradablePauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
function __Pausable_init(address sender) public initializer {
UpgradablePauserRole.__PauserRol_init(sender);
_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 Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// Dependency file: contracts/zeppelin/upgradable/ownership/UpgradableOwnable.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
// import "contracts/zeppelin/upgradable/Initializable.sol";
// import "contracts/zeppelin/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 aplied to your functions to restrict their use to
* the owner.
*/
contract UpgradableOwnable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize(address sender) public initializer {
_owner = 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 _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 zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// Dependency file: contracts/zeppelin/introspection/IERC1820Registry.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
/**
* @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);
}
// Dependency file: contracts/zeppelin/token/ERC777/IERC777Recipient.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
/**
* @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
* [ERC1820 global registry](https://eips.ethereum.org/EIPS/eip-1820).
*
* 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,
uint amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// Dependency file: contracts/zeppelin/token/ERC20/IERC20.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
/**
* @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);
}
// Dependency file: contracts/zeppelin/math/SafeMath.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
/**
* @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: contracts/zeppelin/utils/Address.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
/**
* @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 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: 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);
}
}
}
}
// Dependency file: contracts/zeppelin/token/ERC20/SafeERC20.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
// import "contracts/zeppelin/token/ERC20/IERC20.sol";
// import "contracts/zeppelin/math/SafeMath.sol";
// import "contracts/zeppelin/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 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 non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Dependency file: contracts/zeppelin/token/ERC777/IERC777.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* [ERC1820 registry standard](https://eips.ethereum.org/EIPS/eip-1820) 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 `tokensReceived`
* 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 Make an account an operator of 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 `tokensReceived`
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destoys `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
);
function decimals() external returns (uint8);
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);
}
// Dependency file: contracts/LibEIP712.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
// https://github.com/0xProject/0x-monorepo/blob/development/contracts/utils/contracts/src/LibEIP712.sol
library LibEIP712 {
// Hash of the EIP712 Domain Separator Schema
// keccak256(abi.encodePacked(
// "EIP712Domain(",
// "string name,",
// "string version,",
// "uint256 chainId,",
// "address verifyingContract",
// ")"
// ))
bytes32 constant internal _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev Calculates a EIP712 domain separator.
/// @param name The EIP712 domain name.
/// @param version The EIP712 domain version.
/// @param verifyingContract The EIP712 verifying contract.
/// @return result EIP712 domain separator.
function hashEIP712Domain(
string memory name,
string memory version,
uint256 chainId,
address verifyingContract
)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH;
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
// keccak256(bytes(name)),
// keccak256(bytes(version)),
// chainId,
// uint256(verifyingContract)
// ))
// solium-disable-next-line security/no-inline-assembly
assembly {
// Calculate hashes of dynamic data
let nameHash := keccak256(add(name, 32), mload(name))
let versionHash := keccak256(add(version, 32), mload(version))
// Load free memory pointer
let memPtr := mload(64)
// Store params in memory
mstore(memPtr, schemaHash)
mstore(add(memPtr, 32), nameHash)
mstore(add(memPtr, 64), versionHash)
mstore(add(memPtr, 96), chainId)
mstore(add(memPtr, 128), verifyingContract)
// Compute hash
result := keccak256(memPtr, 160)
}
return result;
}
/// @dev Calculates EIP712 encoding for a hash struct with a given domain hash.
/// @param eip712DomainHash Hash of the domain domain separator data, computed
/// with getDomainHash().
/// @param hashStruct The EIP712 hash struct.
/// @return result EIP712 hash applied to the given EIP712 Domain.
function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct)
internal
pure
returns (bytes32 result)
{
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// EIP191_HEADER,
// EIP712_DOMAIN_HASH,
// hashStruct
// ));
// solium-disable-next-line security/no-inline-assembly
assembly {
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header
mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash
mstore(add(memPtr, 34), hashStruct) // Hash of struct
// Compute hash
result := keccak256(memPtr, 66)
}
return result;
}
}
// Dependency file: contracts/LibUtils.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
library LibUtils {
function decimalsToGranularity(uint8 decimals) internal pure returns (uint256) {
require(decimals <= 18, "LibUtils: Decimals not <= 18");
return uint256(10)**(18-decimals);
}
function getDecimals(address tokenToUse) internal view returns (uint8) {
//support decimals as uint256 or uint8
(bool success, bytes memory data) = tokenToUse.staticcall(abi.encodeWithSignature("decimals()"));
require(success, "LibUtils: No decimals");
// uint<M>: enc(X) is the big-endian encoding of X,
//padded on the higher-order (left) side with zero-bytes such that the length is 32 bytes.
return uint8(abi.decode(data, (uint256)));
}
function getGranularity(address tokenToUse) internal view returns (uint256) {
//support granularity if ERC777
(bool success, bytes memory data) = tokenToUse.staticcall(abi.encodeWithSignature("granularity()"));
require(success, "LibUtils: No granularity");
return abi.decode(data, (uint256));
}
function bytesToAddress(bytes memory bys) internal pure returns (address addr) {
// solium-disable-next-line security/no-inline-assembly
assembly {
addr := mload(add(bys,20))
}
}
}
// Dependency file: contracts/IBridge.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
interface IBridge {
struct ClaimData {
address payable to;
uint256 amount;
bytes32 blockHash;
bytes32 transactionHash;
uint32 logIndex;
}
function version() external pure returns (string memory);
function getFeePercentage() external view returns(uint);
/**
* ERC-20 tokens approve and transferFrom pattern
* See https://eips.ethereum.org/EIPS/eip-20#transferfrom
*/
function receiveTokensTo(address tokenToUse, address to, uint256 amount) external;
/**
* Use network currency and cross it.
*/
function depositTo(address to) external payable;
/**
* ERC-777 tokensReceived hook allows to send tokens to a contract and notify it in a single transaction
* See https://eips.ethereum.org/EIPS/eip-777#motivation for details
*/
function tokensReceived (
address operator,
address from,
address to,
uint amount,
bytes calldata userData,
bytes calldata operatorData
) external;
/**
* Accepts the transaction from the other chain that was voted and sent by the Federation contract
*/
function acceptTransfer(
address _originalTokenAddress,
address payable _from,
address payable _to,
uint256 _amount,
bytes32 _blockHash,
bytes32 _transactionHash,
uint32 _logIndex
) external;
/**
* Claims the crossed transaction using the hash, this sends the funds to the address indicated in
*/
function claim(ClaimData calldata _claimData) external returns (uint256 receivedAmount);
function claimFallback(ClaimData calldata _claimData) external returns (uint256 receivedAmount);
function claimGasless(
ClaimData calldata _claimData,
address payable _relayer,
uint256 _fee,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external returns (uint256 receivedAmount);
function getTransactionDataHash(
address _to,
uint256 _amount,
bytes32 _blockHash,
bytes32 _transactionHash,
uint32 _logIndex
) external returns(bytes32);
event Cross(
address indexed _tokenAddress,
address indexed _from,
address indexed _to,
uint256 _amount,
bytes _userData
);
event NewSideToken(
address indexed _newSideTokenAddress,
address indexed _originalTokenAddress,
string _newSymbol,
uint256 _granularity
);
event AcceptedCrossTransfer(
bytes32 indexed _transactionHash,
address indexed _originalTokenAddress,
address indexed _to,
address _from,
uint256 _amount,
bytes32 _blockHash,
uint256 _logIndex
);
event FeePercentageChanged(uint256 _amount);
event Claimed(
bytes32 indexed _transactionHash,
address indexed _originalTokenAddress,
address indexed _to,
address _sender,
uint256 _amount,
bytes32 _blockHash,
uint256 _logIndex,
address _reciever,
address _relayer,
uint256 _fee
);
}
// Dependency file: contracts/ISideToken.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
interface ISideToken {
function mint(address account, uint256 amount, bytes calldata userData, bytes calldata operatorData) external;
}
// Dependency file: contracts/ISideTokenFactory.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
interface ISideTokenFactory {
function createSideToken(string calldata name, string calldata symbol, uint256 granularity) external returns(address);
event SideTokenCreated(address indexed sideToken, string symbol, uint256 granularity);
}
// Dependency file: contracts/IAllowTokens.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
interface IAllowTokens {
struct Limits {
uint256 min;
uint256 max;
uint256 daily;
uint256 mediumAmount;
uint256 largeAmount;
}
struct TokenInfo {
bool allowed;
uint256 typeId;
uint256 spentToday;
uint256 lastDay;
}
struct TypeInfo {
string description;
Limits limits;
}
struct TokensAndType {
address token;
uint256 typeId;
}
function version() external pure returns (string memory);
function getInfoAndLimits(address token) external view returns (TokenInfo memory info, Limits memory limit);
function calcMaxWithdraw(address token) external view returns (uint256 maxWithdraw);
function getTypesLimits() external view returns(Limits[] memory limits);
function getTypeDescriptionsLength() external view returns(uint256);
function getTypeDescriptions() external view returns(string[] memory descriptions);
function setToken(address token, uint256 typeId) external;
function getConfirmations() external view returns (uint256 smallAmount, uint256 mediumAmount, uint256 largeAmount);
function isTokenAllowed(address token) external view returns (bool);
function updateTokenTransfer(address token, uint256 amount) external;
}
// Dependency file: contracts/IWrapped.sol
// pragma solidity ^0.7.0;
// pragma abicoder v2;
interface IWrapped {
function balanceOf(address) external returns(uint);
function deposit() external payable;
function withdraw(uint wad) external;
function totalSupply() external view returns (uint);
function approve(address guy, uint wad) external returns (bool);
function transfer(address dst, uint wad) external returns (bool);
function transferFrom(address src, address dst, uint wad)
external
returns (bool);
}
// Root file: contracts/Bridge.sol
pragma solidity ^0.7.0;
pragma abicoder v2;
// Import base Initializable contract
// import "contracts/zeppelin/upgradable/Initializable.sol";
// Import interface and library from OpenZeppelin contracts
// import "contracts/zeppelin/upgradable/utils/ReentrancyGuard.sol";
// import "contracts/zeppelin/upgradable/lifecycle/UpgradablePausable.sol";
// import "contracts/zeppelin/upgradable/ownership/UpgradableOwnable.sol";
// import "contracts/zeppelin/introspection/IERC1820Registry.sol";
// import "contracts/zeppelin/token/ERC777/IERC777Recipient.sol";
// import "contracts/zeppelin/token/ERC20/IERC20.sol";
// import "contracts/zeppelin/token/ERC20/SafeERC20.sol";
// import "contracts/zeppelin/utils/Address.sol";
// import "contracts/zeppelin/math/SafeMath.sol";
// import "contracts/zeppelin/token/ERC777/IERC777.sol";
// import "contracts/LibEIP712.sol";
// import "contracts/LibUtils.sol";
// import "contracts/IBridge.sol";
// import "contracts/ISideToken.sol";
// import "contracts/ISideTokenFactory.sol";
// import "contracts/IAllowTokens.sol";
// import "contracts/IWrapped.sol";
contract Bridge is Initializable, IBridge, IERC777Recipient, UpgradablePausable, UpgradableOwnable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
address constant internal NULL_ADDRESS = address(0);
bytes32 constant internal NULL_HASH = bytes32(0);
IERC1820Registry constant internal erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
address internal federation;
uint256 internal feePercentage;
string public symbolPrefix;
bytes32 public DOMAIN_SEPARATOR; // replaces uint256 internal _depprecatedLastDay;
uint256 internal _deprecatedSpentToday;
mapping (address => address) public mappedTokens; // OirignalToken => SideToken
mapping (address => address) public originalTokens; // SideToken => OriginalToken
mapping (address => bool) public knownTokens; // OriginalToken => true
mapping (bytes32 => bool) public claimed; // transactionDataHash => true // previously named processed
IAllowTokens public allowTokens;
ISideTokenFactory public sideTokenFactory;
//Bridge_v1 variables
bool public isUpgrading;
uint256 constant public feePercentageDivider = 10000; // Porcentage with up to 2 decimals
//Bridge_v3 variables
bytes32 constant internal _erc777Interface = keccak256("ERC777Token");
IWrapped public wrappedCurrency;
mapping (bytes32 => bytes32) public transactionsDataHashes; // transactionHash => transactionDataHash
mapping (bytes32 => address) public originalTokenAddresses; // transactionHash => originalTokenAddress
mapping (bytes32 => address) public senderAddresses; // transactionHash => senderAddress
// keccak256("Claim(address to,uint256 amount,bytes32 transactionHash,address relayer,uint256 fee,uint256 nonce,uint256 deadline)");
bytes32 public constant CLAIM_TYPEHASH = 0xf18ceda3f6355f78c234feba066041a50f6557bfb600201e2a71a89e2dd80433;
mapping(address => uint) public nonces;
event AllowTokensChanged(address _newAllowTokens);
event FederationChanged(address _newFederation);
event SideTokenFactoryChanged(address _newSideTokenFactory);
event Upgrading(bool _isUpgrading);
event WrappedCurrencyChanged(address _wrappedCurrency);
function initialize(
address _manager,
address _federation,
address _allowTokens,
address _sideTokenFactory,
string memory _symbolPrefix
) public initializer {
UpgradableOwnable.initialize(_manager);
UpgradablePausable.__Pausable_init(_manager);
symbolPrefix = _symbolPrefix;
allowTokens = IAllowTokens(_allowTokens);
sideTokenFactory = ISideTokenFactory(_sideTokenFactory);
federation = _federation;
//keccak256("ERC777TokensRecipient")
erc1820.setInterfaceImplementer(address(this), 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b, address(this));
initDomainSeparator();
}
receive () external payable {
// The fallback function is needed to use WRBTC
require(_msgSender() == address(wrappedCurrency), "Bridge: not wrappedCurrency");
}
function version() override external pure returns (string memory) {
return "v3";
}
function initDomainSeparator() public {
uint chainId;
// solium-disable-next-line security/no-inline-assembly
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = LibEIP712.hashEIP712Domain(
"RSK Token Bridge",
"1",
chainId,
address(this)
);
}
modifier whenNotUpgrading() {
require(!isUpgrading, "Bridge: Upgrading");
_;
}
function acceptTransfer(
address _originalTokenAddress,
address payable _from,
address payable _to,
uint256 _amount,
bytes32 _blockHash,
bytes32 _transactionHash,
uint32 _logIndex
) external whenNotPaused nonReentrant override {
require(_msgSender() == federation, "Bridge: Not Federation");
require(knownTokens[_originalTokenAddress] ||
mappedTokens[_originalTokenAddress] != NULL_ADDRESS,
"Bridge: Unknown token"
);
require(_to != NULL_ADDRESS, "Bridge: Null To");
require(_amount > 0, "Bridge: Amount 0");
require(_blockHash != NULL_HASH, "Bridge: Null BlockHash");
require(_transactionHash != NULL_HASH, "Bridge: Null TxHash");
require(transactionsDataHashes[_transactionHash] == bytes32(0), "Bridge: Already accepted");
bytes32 _transactionDataHash = getTransactionDataHash(
_to,
_amount,
_blockHash,
_transactionHash,
_logIndex
);
// Do not remove, claimed also has the previously processed using the older bridge version
// https://github.com/rsksmart/tokenbridge/blob/TOKENBRIDGE-1.2.0/bridge/contracts/Bridge.sol#L41
require(!claimed[_transactionDataHash], "Bridge: Already claimed");
transactionsDataHashes[_transactionHash] = _transactionDataHash;
originalTokenAddresses[_transactionHash] = _originalTokenAddress;
senderAddresses[_transactionHash] = _from;
emit AcceptedCrossTransfer(
_transactionHash,
_originalTokenAddress,
_to,
_from,
_amount,
_blockHash,
_logIndex
);
}
function createSideToken(
uint256 _typeId,
address _originalTokenAddress,
uint8 _originalTokenDecimals,
string calldata _originalTokenSymbol,
string calldata _originalTokenName
) external onlyOwner {
require(_originalTokenAddress != NULL_ADDRESS, "Bridge: Null token");
address sideToken = mappedTokens[_originalTokenAddress];
require(sideToken == NULL_ADDRESS, "Bridge: Already exists");
uint256 granularity = LibUtils.decimalsToGranularity(_originalTokenDecimals);
string memory newSymbol = string(abi.encodePacked(symbolPrefix, _originalTokenSymbol));
// Create side token
sideToken = sideTokenFactory.createSideToken(_originalTokenName, newSymbol, granularity);
mappedTokens[_originalTokenAddress] = sideToken;
originalTokens[sideToken] = _originalTokenAddress;
allowTokens.setToken(sideToken, _typeId);
emit NewSideToken(sideToken, _originalTokenAddress, newSymbol, granularity);
}
function claim(ClaimData calldata _claimData)
external override returns (uint256 receivedAmount) {
receivedAmount = _claim(
_claimData,
_claimData.to,
payable(address(0)),
0
);
return receivedAmount;
}
function claimFallback(ClaimData calldata _claimData)
external override returns (uint256 receivedAmount) {
require(_msgSender() == senderAddresses[_claimData.transactionHash],"Bridge: invalid sender");
receivedAmount = _claim(
_claimData,
_msgSender(),
payable(address(0)),
0
);
return receivedAmount;
}
function getDigest(
ClaimData memory _claimData,
address payable _relayer,
uint256 _fee,
uint256 _deadline
) internal returns (bytes32) {
return LibEIP712.hashEIP712Message(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
CLAIM_TYPEHASH,
_claimData.to,
_claimData.amount,
_claimData.transactionHash,
_relayer,
_fee,
nonces[_claimData.to]++,
_deadline
)
)
);
}
// Inspired by https://github.com/dapphub/ds-dach/blob/master/src/dach.sol
function claimGasless(
ClaimData calldata _claimData,
address payable _relayer,
uint256 _fee,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external override returns (uint256 receivedAmount) {
require(_deadline >= block.timestamp, "Bridge: EXPIRED");
bytes32 digest = getDigest(_claimData, _relayer, _fee, _deadline);
address recoveredAddress = ecrecover(digest, _v, _r, _s);
require(_claimData.to != address(0) && recoveredAddress == _claimData.to, "Bridge: INVALID_SIGNATURE");
receivedAmount = _claim(
_claimData,
_claimData.to,
_relayer,
_fee
);
return receivedAmount;
}
function _claim(
ClaimData calldata _claimData,
address payable _reciever,
address payable _relayer,
uint256 _fee
) internal nonReentrant returns (uint256 receivedAmount) {
address originalTokenAddress = originalTokenAddresses[_claimData.transactionHash];
require(originalTokenAddress != NULL_ADDRESS, "Bridge: Tx not crossed");
bytes32 transactionDataHash = getTransactionDataHash(
_claimData.to,
_claimData.amount,
_claimData.blockHash,
_claimData.transactionHash,
_claimData.logIndex
);
require(transactionsDataHashes[_claimData.transactionHash] == transactionDataHash, "Bridge: Wrong transactionDataHash");
require(!claimed[transactionDataHash], "Bridge: Already claimed");
claimed[transactionDataHash] = true;
if (knownTokens[originalTokenAddress]) {
receivedAmount =_claimCrossBackToToken(
originalTokenAddress,
_reciever,
_claimData.amount,
_relayer,
_fee
);
} else {
receivedAmount =_claimCrossToSideToken(
originalTokenAddress,
_reciever,
_claimData.amount,
_relayer,
_fee
);
}
emit Claimed(
_claimData.transactionHash,
originalTokenAddress,
_claimData.to,
senderAddresses[_claimData.transactionHash],
_claimData.amount,
_claimData.blockHash,
_claimData.logIndex,
_reciever,
_relayer,
_fee
);
return receivedAmount;
}
function _claimCrossToSideToken(
address _originalTokenAddress,
address payable _receiver,
uint256 _amount,
address payable _relayer,
uint256 _fee
) internal returns (uint256 receivedAmount) {
address sideToken = mappedTokens[_originalTokenAddress];
uint256 granularity = IERC777(sideToken).granularity();
uint256 formattedAmount = _amount.mul(granularity);
require(_fee <= formattedAmount, "Bridge: fee too high");
receivedAmount = formattedAmount - _fee;
ISideToken(sideToken).mint(_receiver, receivedAmount, "", "");
if(_fee > 0) {
ISideToken(sideToken).mint(_relayer, _fee, "", "relayer fee");
}
return receivedAmount;
}
function _claimCrossBackToToken(
address _originalTokenAddress,
address payable _receiver,
uint256 _amount,
address payable _relayer,
uint256 _fee
) internal returns (uint256 receivedAmount) {
uint256 decimals = LibUtils.getDecimals(_originalTokenAddress);
//As side tokens are ERC777 they will always have 18 decimals
uint256 formattedAmount = _amount.div(uint256(10) ** (18 - decimals));
require(_fee <= formattedAmount, "Bridge: fee too high");
receivedAmount = formattedAmount - _fee;
if(address(wrappedCurrency) == _originalTokenAddress) {
wrappedCurrency.withdraw(formattedAmount);
_receiver.transfer(receivedAmount);
if(_fee > 0) {
_relayer.transfer(_fee);
}
} else {
IERC20(_originalTokenAddress).safeTransfer(_receiver, receivedAmount);
if(_fee > 0) {
IERC20(_originalTokenAddress).safeTransfer(_relayer, _fee);
}
}
return receivedAmount;
}
/**
* ERC-20 tokens approve and transferFrom pattern
* See https://eips.ethereum.org/EIPS/eip-20#transferfrom
*/
function receiveTokensTo(address tokenToUse, address to, uint256 amount) override public {
address sender = _msgSender();
//Transfer the tokens on IERC20, they should be already Approved for the bridge Address to use them
IERC20(tokenToUse).safeTransferFrom(sender, address(this), amount);
crossTokens(tokenToUse, sender, to, amount, "");
}
/**
* Use network currency and cross it.
*/
function depositTo(address to) override external payable {
address sender = _msgSender();
require(address(wrappedCurrency) != NULL_ADDRESS, "Bridge: wrappedCurrency empty");
wrappedCurrency.deposit{ value: msg.value }();
crossTokens(address(wrappedCurrency), sender, to, msg.value, "");
}
/**
* ERC-777 tokensReceived hook allows to send tokens to a contract and notify it in a single transaction
* See https://eips.ethereum.org/EIPS/eip-777#motivation for details
*/
function tokensReceived (
address operator,
address from,
address to,
uint amount,
bytes calldata userData,
bytes calldata
) external override(IBridge, IERC777Recipient){
//Hook from ERC777address
if(operator == address(this)) return; // Avoid loop from bridge calling to ERC77transferFrom
require(to == address(this), "Bridge: Not to this address");
address tokenToUse = _msgSender();
require(erc1820.getInterfaceImplementer(tokenToUse, _erc777Interface) != NULL_ADDRESS, "Bridge: Not ERC777 token");
require(userData.length != 0 || !from.isContract(), "Bridge: Specify receiver address in data");
address receiver = userData.length == 0 ? from : LibUtils.bytesToAddress(userData);
crossTokens(tokenToUse, from, receiver, amount, userData);
}
function crossTokens(address tokenToUse, address from, address to, uint256 amount, bytes memory userData)
internal whenNotUpgrading whenNotPaused nonReentrant {
knownTokens[tokenToUse] = true;
uint256 fee = amount.mul(feePercentage).div(feePercentageDivider);
uint256 amountMinusFees = amount.sub(fee);
uint8 decimals = LibUtils.getDecimals(tokenToUse);
uint formattedAmount = amount;
if(decimals != 18) {
formattedAmount = amount.mul(uint256(10)**(18-decimals));
}
// We consider the amount before fees converted to 18 decimals to check the limits
// updateTokenTransfer revert if token not allowed
allowTokens.updateTokenTransfer(tokenToUse, formattedAmount);
address originalTokenAddress = tokenToUse;
if (originalTokens[tokenToUse] != NULL_ADDRESS) {
//Side Token Crossing
originalTokenAddress = originalTokens[tokenToUse];
uint256 granularity = LibUtils.getGranularity(tokenToUse);
uint256 modulo = amountMinusFees.mod(granularity);
fee = fee.add(modulo);
amountMinusFees = amountMinusFees.sub(modulo);
IERC777(tokenToUse).burn(amountMinusFees, userData);
}
emit Cross(
originalTokenAddress,
from,
to,
amountMinusFees,
userData
);
if (fee > 0) {
//Send the payment to the MultiSig of the Federation
IERC20(tokenToUse).safeTransfer(owner(), fee);
}
}
function getTransactionDataHash(
address _to,
uint256 _amount,
bytes32 _blockHash,
bytes32 _transactionHash,
uint32 _logIndex
)
public pure override returns(bytes32)
{
return keccak256(abi.encodePacked(_blockHash, _transactionHash, _to, _amount, _logIndex));
}
function setFeePercentage(uint amount) external onlyOwner {
require(amount < (feePercentageDivider/10), "Bridge: bigger than 10%");
feePercentage = amount;
emit FeePercentageChanged(feePercentage);
}
function getFeePercentage() external view override returns(uint) {
return feePercentage;
}
function changeFederation(address newFederation) external onlyOwner {
require(newFederation != NULL_ADDRESS, "Bridge: Federation is empty");
federation = newFederation;
emit FederationChanged(federation);
}
function changeAllowTokens(address newAllowTokens) external onlyOwner {
require(newAllowTokens != NULL_ADDRESS, "Bridge: AllowTokens is empty");
allowTokens = IAllowTokens(newAllowTokens);
emit AllowTokensChanged(newAllowTokens);
}
function getFederation() external view returns(address) {
return federation;
}
function changeSideTokenFactory(address newSideTokenFactory) external onlyOwner {
require(newSideTokenFactory != NULL_ADDRESS, "Bridge: SideTokenFactory is empty");
sideTokenFactory = ISideTokenFactory(newSideTokenFactory);
emit SideTokenFactoryChanged(newSideTokenFactory);
}
function setUpgrading(bool _isUpgrading) external onlyOwner {
isUpgrading = _isUpgrading;
emit Upgrading(isUpgrading);
}
function setWrappedCurrency(address _wrappedCurrency) external onlyOwner {
require(_wrappedCurrency != NULL_ADDRESS, "Bridge: wrapp is empty");
wrappedCurrency = IWrapped(_wrappedCurrency);
emit WrappedCurrencyChanged(_wrappedCurrency);
}
function hasCrossed(bytes32 transactionHash) public view returns (bool) {
return transactionsDataHashes[transactionHash] != bytes32(0);
}
function hasBeenClaimed(bytes32 transactionHash) public view returns (bool) {
return claimed[transactionsDataHashes[transactionHash]];
}
} | * @title Helps contracts guard against reentrancy attacks. @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> @dev If you mark a function `nonReentrant`, you should also mark it `external`./ | contract ReentrancyGuard is Initializable {
uint256 private _guardCounter;
function initialize() public initializer {
_guardCounter = 1;
}
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: no reentrant allowed");
}
}
| 11,909,114 | [
1,
44,
292,
1121,
20092,
11026,
5314,
283,
8230,
12514,
28444,
18,
225,
2663,
2894,
605,
383,
351,
275,
411,
2764,
2894,
36,
22,
144,
227,
18,
832,
20401,
512,
275,
8906,
411,
287,
338,
402,
36,
14860,
3890,
18,
1594,
34,
225,
971,
1846,
2267,
279,
445,
1375,
5836,
426,
8230,
970,
9191,
1846,
1410,
2546,
2267,
518,
1375,
9375,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
868,
8230,
12514,
16709,
353,
10188,
6934,
288,
203,
565,
2254,
5034,
3238,
389,
24594,
4789,
31,
203,
203,
203,
203,
203,
565,
445,
4046,
1435,
1071,
12562,
288,
203,
3639,
389,
24594,
4789,
273,
404,
31,
203,
565,
289,
203,
203,
565,
9606,
1661,
426,
8230,
970,
1435,
288,
203,
3639,
389,
24594,
4789,
1011,
404,
31,
203,
3639,
2254,
5034,
1191,
4789,
273,
389,
24594,
4789,
31,
203,
3639,
389,
31,
203,
3639,
2583,
12,
3729,
4789,
422,
389,
24594,
4789,
16,
315,
426,
8230,
12514,
16709,
30,
1158,
283,
8230,
970,
2935,
8863,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.4;
/// @title Bitplus Token (BPNT) - crowdfunding code for Bitplus Project
contract BitplusToken {
string public constant name = "Bitplus Token";
string public constant symbol = "BPNT";
uint8 public constant decimals = 18; // 18 decimal places, the same as ETH.
uint256 public constant tokenCreationRate = 1000;
// The funding cap in weis.
uint256 public constant tokenCreationCap = 25000 ether * tokenCreationRate;
uint256 public constant tokenCreationMin = 2500 ether * tokenCreationRate;
uint256 public fundingStartBlock;
uint256 public fundingEndBlock;
// The flag indicates if the GNT contract is in Funding state.
bool public funding = true;
// Receives ETH
address public bitplusAddress;
// The current total token supply.
uint256 totalTokens;
mapping (address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) allowed;
struct EarlyBackerCondition {
address backerAddress;
uint256 deposited;
uint256 agreedPercentage;
uint256 agreedEthPrice;
}
EarlyBackerCondition[] public earlyBackers;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Refund(address indexed _from, uint256 _value);
event EarlyBackerDeposit(address indexed _from, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function BitplusToken(uint256 _fundingStartBlock,
uint256 _fundingEndBlock) {
address _bitplusAddress = 0x286e0060d9DBEa0231389485D455A80f14648B3c;
if (_bitplusAddress == 0) throw;
if (_fundingStartBlock <= block.number) throw;
if (_fundingEndBlock <= _fundingStartBlock) throw;
// special conditions for the early backers
earlyBackers.push(EarlyBackerCondition({
backerAddress: 0xa1cfc9ebdffbffe9b27d741ae04cfc2e78af527a,
deposited: 0,
agreedPercentage: 1000,
agreedEthPrice: 250 ether
}));
// conditions for the company / developers
earlyBackers.push(EarlyBackerCondition({
backerAddress: 0x37ef1168252f274D4cA5b558213d7294085BCA08,
deposited: 0,
agreedPercentage: 500,
agreedEthPrice: 0.1 ether
}));
earlyBackers.push(EarlyBackerCondition({
backerAddress: 0x246604643ac38e96526b66ba91c1b2ec0c39d8de,
deposited: 0,
agreedPercentage: 500,
agreedEthPrice: 0.1 ether
}));
bitplusAddress = _bitplusAddress;
fundingStartBlock = _fundingStartBlock;
fundingEndBlock = _fundingEndBlock;
}
/// @notice Transfer `_value` BPNT tokens from sender's account
/// `msg.sender` to provided account address `_to`.
/// @notice This function is disabled during the funding.
/// @dev Required state: Operational
/// @param _to The address of the tokens recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool) {
// Abort if not in Operational state.
if (funding) throw;
var senderBalance = balances[msg.sender];
if (senderBalance >= _value && _value > 0) {
senderBalance -= _value;
balances[msg.sender] = senderBalance;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
return false;
}
function transferFrom(
address _from,
address _to,
uint256 _amount
) returns (bool success) {
// Abort if not in Operational state.
if (funding) throw;
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
return true;
} else {
return false;
}
}
function totalSupply() external constant returns (uint256) {
return totalTokens;
}
function balanceOf(address _owner) external constant returns (uint256) {
return balances[_owner];
}
/// @notice Create tokens when funding is active.
/// @dev Required state: Funding Active
/// @dev State transition: -> Funding Success (only if cap reached)
function create() payable external {
// Abort if not in Funding Active state.
// The checks are split (instead of using or operator) because it is
// cheaper this way.
if (!funding) throw;
if (block.number < fundingStartBlock) throw;
if (block.number > fundingEndBlock) throw;
// Do not allow creating 0 tokens.
if (msg.value == 0) throw;
bool isEarlyBacker = false;
for (uint i = 0; i < earlyBackers.length; i++) {
if(earlyBackers[i].backerAddress == msg.sender) {
earlyBackers[i].deposited += msg.value;
isEarlyBacker = true;
EarlyBackerDeposit(msg.sender, msg.value);
}
}
if(!isEarlyBacker) {
// do not allow to create more then cap tokens
if (msg.value > (tokenCreationCap - totalTokens) / tokenCreationRate)
throw;
var numTokens = msg.value * tokenCreationRate;
totalTokens += numTokens;
// Assign new tokens to the sender
balances[msg.sender] += numTokens;
// Log token creation event
Transfer(0, msg.sender, numTokens);
}
}
/// @notice Finalize crowdfunding
/// @dev If cap was reached or crowdfunding has ended then:
/// create BPNT for the early backers,
/// transfer ETH to the Bitplus address.
/// @dev Required state: Funding Success
/// @dev State transition: -> Operational Normal
function finalize() external {
// Abort if not in Funding Success state.
if (!funding) throw;
if ((block.number <= fundingEndBlock ||
totalTokens < tokenCreationMin) &&
totalTokens < tokenCreationCap) throw;
// Switch to Operational state. This is the only place this can happen.
funding = false;
// Transfer ETH to the Bitplus address.
if (!bitplusAddress.send(this.balance)) throw;
for (uint i = 0; i < earlyBackers.length; i++) {
if(earlyBackers[i].deposited != uint256(0)) {
uint256 percentage = (earlyBackers[i].deposited * earlyBackers[i].agreedPercentage / earlyBackers[i].agreedEthPrice);
uint256 additionalTokens = totalTokens * percentage / (10000 - percentage);
address backerAddr = earlyBackers[i].backerAddress;
balances[backerAddr] = additionalTokens;
totalTokens += additionalTokens;
Transfer(0, backerAddr, additionalTokens);
}
}
}
/// @notice Get back the ether sent during the funding in case the funding
/// has not reached the minimum level.
/// @dev Required state: Funding Failure
function refund() external {
// Abort if not in Funding Failure state.
if (!funding) throw;
if (block.number <= fundingEndBlock) throw;
if (totalTokens >= tokenCreationMin) throw;
bool isEarlyBacker = false;
uint256 ethValue;
for (uint i = 0; i < earlyBackers.length; i++) {
if(earlyBackers[i].backerAddress == msg.sender) {
isEarlyBacker = true;
ethValue = earlyBackers[i].deposited;
if (ethValue == 0) throw;
}
}
if(!isEarlyBacker) {
var bpntValue = balances[msg.sender];
if (bpntValue == 0) throw;
balances[msg.sender] = 0;
totalTokens -= bpntValue;
ethValue = bpntValue / tokenCreationRate;
}
Refund(msg.sender, ethValue);
if (!msg.sender.send(ethValue)) throw;
}
// Allow _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.
function approve(address _spender, uint256 _amount) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
// Just a safeguard for people who might invest and then loose the key
// If 2 weeks after an unsuccessful end of the campaign there are unclaimed
// funds, transfer those to Bitplus address - the funds will be returned to
// respective owners from it
function safeguard() {
if(block.number > (fundingEndBlock + 71000)) {
if (!bitplusAddress.send(this.balance)) throw;
}
}
}
| Abort if not in Operational state. | function transferFrom(
address _from,
address _to,
uint256 _amount
) returns (bool success) {
if (funding) throw;
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
return true;
return false;
}
}
| 12,815,881 | [
1,
13572,
309,
486,
316,
4189,
287,
919,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7412,
1265,
12,
203,
540,
1758,
389,
2080,
16,
203,
540,
1758,
389,
869,
16,
203,
540,
2254,
5034,
389,
8949,
203,
377,
262,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
309,
261,
74,
14351,
13,
604,
31,
1850,
203,
1850,
203,
540,
309,
261,
70,
26488,
63,
67,
2080,
65,
1545,
389,
8949,
203,
2398,
597,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
65,
1545,
389,
8949,
203,
2398,
597,
389,
8949,
405,
374,
13,
288,
203,
2398,
324,
26488,
63,
67,
2080,
65,
3947,
389,
8949,
31,
203,
2398,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
65,
3947,
389,
8949,
31,
203,
2398,
324,
26488,
63,
67,
869,
65,
1011,
389,
8949,
31,
203,
2398,
327,
638,
31,
203,
2398,
327,
629,
31,
203,
540,
289,
203,
565,
289,
377,
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
]
|
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: Account
library Account {
enum Status {Normal, Liquid, Vapor}
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
struct Storage {
mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal
Status status;
}
}
// Part: Actions
library Actions {
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (publicly)
Sell, // sell an amount of some token (publicly)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary}
enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct DepositArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address from;
}
struct WithdrawArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address to;
}
struct TransferArgs {
Types.AssetAmount amount;
Account.Info accountOne;
Account.Info accountTwo;
uint256 market;
}
struct BuyArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 makerMarket;
uint256 takerMarket;
address exchangeWrapper;
bytes orderData;
}
struct SellArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 takerMarket;
uint256 makerMarket;
address exchangeWrapper;
bytes orderData;
}
struct TradeArgs {
Types.AssetAmount amount;
Account.Info takerAccount;
Account.Info makerAccount;
uint256 inputMarket;
uint256 outputMarket;
address autoTrader;
bytes tradeData;
}
struct LiquidateArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info liquidAccount;
uint256 owedMarket;
uint256 heldMarket;
}
struct VaporizeArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info vaporAccount;
uint256 owedMarket;
uint256 heldMarket;
}
struct CallArgs {
Account.Info account;
address callee;
bytes data;
}
}
// Part: IAaveIncentivesController
interface IAaveIncentivesController {
/**
* @dev Returns the total of rewards of an user, already accrued + not yet accrued
* @param user The address of the user
* @return The rewards
**/
function getRewardsBalance(address[] calldata assets, address user)
external
view
returns (uint256);
/**
* @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards
* @param amount Amount of rewards to claim
* @param to Address that will be receiving the rewards
* @return Rewards claimed
**/
function claimRewards(
address[] calldata assets,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must
* be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager
* @param amount Amount of rewards to claim
* @param user Address to check and claim rewards
* @param to Address that will be receiving the rewards
* @return Rewards claimed
**/
function claimRewardsOnBehalf(
address[] calldata assets,
uint256 amount,
address user,
address to
) external returns (uint256);
/**
* @dev returns the unclaimed rewards of the user
* @param user the address of the user
* @return the unclaimed user rewards
*/
function getUserUnclaimedRewards(address user)
external
view
returns (uint256);
/**
* @dev for backward compatibility with previous implementation of the Incentives controller
*/
function REWARD_TOKEN() external view returns (address);
function getDistributionEnd() external view returns (uint256);
function getAssetData(address asset)
external
view
returns (
uint256,
uint256,
uint256
);
}
// Part: ICallee
/**
* @title ICallee
* @author dYdX
*
* Interface that Callees for Solo must implement in order to ingest data.
*/
interface ICallee {
// ============ Public Functions ============
/**
* Allows users to send this contract arbitrary data.
*
* @param sender The msg.sender to Solo
* @param accountInfo The account from which the data is being sent
* @param data Arbitrary data given by the sender
*/
function callFunction(
address sender,
Account.Info memory accountInfo,
bytes memory data
) external;
}
// Part: ILendingPoolAddressesProvider
/**
* @title LendingPoolAddressesProvider contract
* @dev Main registry of addresses part of or connected to the protocol, including permissioned roles
* - Acting also as factory of proxies and admin of those, so with right to change its implementations
* - Owned by the Aave Governance
* @author Aave
**/
interface ILendingPoolAddressesProvider {
event MarketIdSet(string newMarketId);
event LendingPoolUpdated(address indexed newAddress);
event ConfigurationAdminUpdated(address indexed newAddress);
event EmergencyAdminUpdated(address indexed newAddress);
event LendingPoolConfiguratorUpdated(address indexed newAddress);
event LendingPoolCollateralManagerUpdated(address indexed newAddress);
event PriceOracleUpdated(address indexed newAddress);
event LendingRateOracleUpdated(address indexed newAddress);
event ProxyCreated(bytes32 id, address indexed newAddress);
event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);
function getMarketId() external view returns (string memory);
function setMarketId(string calldata marketId) external;
function setAddress(bytes32 id, address newAddress) external;
function setAddressAsProxy(bytes32 id, address impl) external;
function getAddress(bytes32 id) external view returns (address);
function getLendingPool() external view returns (address);
function setLendingPoolImpl(address pool) external;
function getLendingPoolConfigurator() external view returns (address);
function setLendingPoolConfiguratorImpl(address configurator) external;
function getLendingPoolCollateralManager() external view returns (address);
function setLendingPoolCollateralManager(address manager) external;
function getPoolAdmin() external view returns (address);
function setPoolAdmin(address admin) external;
function getEmergencyAdmin() external view returns (address);
function setEmergencyAdmin(address admin) external;
function getPriceOracle() external view returns (address);
function setPriceOracle(address priceOracle) external;
function getLendingRateOracle() external view returns (address);
function setLendingRateOracle(address lendingRateOracle) external;
}
// Part: IOptionalERC20
interface IOptionalERC20 {
function decimals() external view returns (uint8);
}
// Part: IPriceOracle
interface IPriceOracle {
function getAssetPrice(address _asset) external view returns (uint256);
function getAssetsPrices(address[] calldata _assets)
external
view
returns (uint256[] memory);
function getSourceOfAsset(address _asset) external view returns (address);
function getFallbackOracle() external view returns (address);
}
// Part: IScaledBalanceToken
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user)
external
view
returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
}
// Part: ISoloMargin
library Decimal {
struct D256 {
uint256 value;
}
}
library Interest {
struct Rate {
uint256 value;
}
struct Index {
uint96 borrow;
uint96 supply;
uint32 lastUpdate;
}
}
library Monetary {
struct Price {
uint256 value;
}
struct Value {
uint256 value;
}
}
library Storage {
// All information necessary for tracking a market
struct Market {
// Contract address of the associated ERC20 token
address token;
// Total aggregated supply and borrow amount of the entire market
Types.TotalPar totalPar;
// Interest index of the market
Interest.Index index;
// Contract address of the price oracle for this market
address priceOracle;
// Contract address of the interest setter for this market
address interestSetter;
// Multiplier on the marginRatio for this market
Decimal.D256 marginPremium;
// Multiplier on the liquidationSpread for this market
Decimal.D256 spreadPremium;
// Whether additional borrows are allowed for this market
bool isClosing;
}
// The global risk parameters that govern the health and security of the system
struct RiskParams {
// Required ratio of over-collateralization
Decimal.D256 marginRatio;
// Percentage penalty incurred by liquidated accounts
Decimal.D256 liquidationSpread;
// Percentage of the borrower's interest fee that gets passed to the suppliers
Decimal.D256 earningsRate;
// The minimum absolute borrow value of an account
// There must be sufficient incentivize to liquidate undercollateralized accounts
Monetary.Value minBorrowedValue;
}
// The maximum RiskParam values that can be set
struct RiskLimits {
uint64 marginRatioMax;
uint64 liquidationSpreadMax;
uint64 earningsRateMax;
uint64 marginPremiumMax;
uint64 spreadPremiumMax;
uint128 minBorrowedValueMax;
}
// The entire storage state of Solo
struct State {
// number of markets
uint256 numMarkets;
// marketId => Market
mapping(uint256 => Market) markets;
// owner => account number => Account
mapping(address => mapping(uint256 => Account.Storage)) accounts;
// Addresses that can control other users accounts
mapping(address => mapping(address => bool)) operators;
// Addresses that can control all users accounts
mapping(address => bool) globalOperators;
// mutable risk parameters of the system
RiskParams riskParams;
// immutable risk limits of the system
RiskLimits riskLimits;
}
}
interface ISoloMargin {
struct OperatorArg {
address operator1;
bool trusted;
}
function ownerSetSpreadPremium(
uint256 marketId,
Decimal.D256 memory spreadPremium
) external;
function getIsGlobalOperator(address operator1)
external
view
returns (bool);
function getMarketTokenAddress(uint256 marketId)
external
view
returns (address);
function ownerSetInterestSetter(uint256 marketId, address interestSetter)
external;
function getAccountValues(Account.Info memory account)
external
view
returns (Monetary.Value memory, Monetary.Value memory);
function getMarketPriceOracle(uint256 marketId)
external
view
returns (address);
function getMarketInterestSetter(uint256 marketId)
external
view
returns (address);
function getMarketSpreadPremium(uint256 marketId)
external
view
returns (Decimal.D256 memory);
function getNumMarkets() external view returns (uint256);
function ownerWithdrawUnsupportedTokens(address token, address recipient)
external
returns (uint256);
function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue)
external;
function ownerSetLiquidationSpread(Decimal.D256 memory spread) external;
function ownerSetEarningsRate(Decimal.D256 memory earningsRate) external;
function getIsLocalOperator(address owner, address operator1)
external
view
returns (bool);
function getAccountPar(Account.Info memory account, uint256 marketId)
external
view
returns (Types.Par memory);
function ownerSetMarginPremium(
uint256 marketId,
Decimal.D256 memory marginPremium
) external;
function getMarginRatio() external view returns (Decimal.D256 memory);
function getMarketCurrentIndex(uint256 marketId)
external
view
returns (Interest.Index memory);
function getMarketIsClosing(uint256 marketId) external view returns (bool);
function getRiskParams() external view returns (Storage.RiskParams memory);
function getAccountBalances(Account.Info memory account)
external
view
returns (
address[] memory,
Types.Par[] memory,
Types.Wei[] memory
);
function renounceOwnership() external;
function getMinBorrowedValue()
external
view
returns (Monetary.Value memory);
function setOperators(OperatorArg[] memory args) external;
function getMarketPrice(uint256 marketId) external view returns (address);
function owner() external view returns (address);
function isOwner() external view returns (bool);
function ownerWithdrawExcessTokens(uint256 marketId, address recipient)
external
returns (uint256);
function ownerAddMarket(
address token,
address priceOracle,
address interestSetter,
Decimal.D256 memory marginPremium,
Decimal.D256 memory spreadPremium
) external;
function operate(
Account.Info[] memory accounts,
Actions.ActionArgs[] memory actions
) external;
function getMarketWithInfo(uint256 marketId)
external
view
returns (
Storage.Market memory,
Interest.Index memory,
Monetary.Price memory,
Interest.Rate memory
);
function ownerSetMarginRatio(Decimal.D256 memory ratio) external;
function getLiquidationSpread() external view returns (Decimal.D256 memory);
function getAccountWei(Account.Info memory account, uint256 marketId)
external
view
returns (Types.Wei memory);
function getMarketTotalPar(uint256 marketId)
external
view
returns (Types.TotalPar memory);
function getLiquidationSpreadForPair(
uint256 heldMarketId,
uint256 owedMarketId
) external view returns (Decimal.D256 memory);
function getNumExcessTokens(uint256 marketId)
external
view
returns (Types.Wei memory);
function getMarketCachedIndex(uint256 marketId)
external
view
returns (Interest.Index memory);
function getAccountStatus(Account.Info memory account)
external
view
returns (uint8);
function getEarningsRate() external view returns (Decimal.D256 memory);
function ownerSetPriceOracle(uint256 marketId, address priceOracle)
external;
function getRiskLimits() external view returns (Storage.RiskLimits memory);
function getMarket(uint256 marketId)
external
view
returns (Storage.Market memory);
function ownerSetIsClosing(uint256 marketId, bool isClosing) external;
function ownerSetGlobalOperator(address operator1, bool approved) external;
function transferOwnership(address newOwner) external;
function getAdjustedAccountValues(Account.Info memory account)
external
view
returns (Monetary.Value memory, Monetary.Value memory);
function getMarketMarginPremium(uint256 marketId)
external
view
returns (Decimal.D256 memory);
function getMarketInterestRate(uint256 marketId)
external
view
returns (Interest.Rate memory);
}
// Part: IStakedAave
interface IStakedAave {
function stake(address to, uint256 amount) external;
function redeem(address to, uint256 amount) external;
function cooldown() external;
function claimRewards(address to, uint256 amount) external;
function getTotalRewardsBalance(address) external view returns (uint256);
function COOLDOWN_SECONDS() external view returns (uint256);
function stakersCooldowns(address) external view returns (uint256);
function UNSTAKE_WINDOW() external view returns (uint256);
}
// Part: IUni
interface IUni{
function getAmountsOut(
uint256 amountIn,
address[] calldata path
) external view returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// Part: IUniswapV3SwapCallback
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Part: OpenZeppelin/[email protected]/Math
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Part: Types
library Types {
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct TotalPar {
uint128 borrow;
uint128 supply;
}
struct Par {
bool sign; // true if positive
uint128 value;
}
struct Wei {
bool sign; // true if positive
uint256 value;
}
}
// Part: yearn/[email protected]/HealthCheck
interface HealthCheck {
function check(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding,
uint256 totalDebt
) external view returns (bool);
}
// Part: ILendingPool
library DataTypes {
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
interface ILendingPool {
/**
* @dev Emitted on deposit()
* @param reserve The address of the underlying asset of the reserve
* @param user The address initiating the deposit
* @param onBehalfOf The beneficiary of the deposit, receiving the aTokens
* @param amount The amount deposited
* @param referral The referral code used
**/
event Deposit(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint16 indexed referral
);
/**
* @dev Emitted on withdraw()
* @param reserve The address of the underlyng asset being withdrawn
* @param user The address initiating the withdrawal, owner of aTokens
* @param to Address that will receive the underlying
* @param amount The amount to be withdrawn
**/
event Withdraw(
address indexed reserve,
address indexed user,
address indexed to,
uint256 amount
);
/**
* @dev Emitted on borrow() and flashLoan() when debt needs to be opened
* @param reserve The address of the underlying asset being borrowed
* @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just
* initiator of the transaction on flashLoan()
* @param onBehalfOf The address that will be getting the debt
* @param amount The amount borrowed out
* @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable
* @param borrowRate The numeric rate at which the user has borrowed
* @param referral The referral code used
**/
event Borrow(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint256 borrowRateMode,
uint256 borrowRate,
uint16 indexed referral
);
/**
* @dev Emitted on repay()
* @param reserve The address of the underlying asset of the reserve
* @param user The beneficiary of the repayment, getting his debt reduced
* @param repayer The address of the user initiating the repay(), providing the funds
* @param amount The amount repaid
**/
event Repay(
address indexed reserve,
address indexed user,
address indexed repayer,
uint256 amount
);
/**
* @dev Emitted on swapBorrowRateMode()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user swapping his rate mode
* @param rateMode The rate mode that the user wants to swap to
**/
event Swap(address indexed reserve, address indexed user, uint256 rateMode);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralEnabled(
address indexed reserve,
address indexed user
);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralDisabled(
address indexed reserve,
address indexed user
);
/**
* @dev Emitted on rebalanceStableBorrowRate()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user for which the rebalance has been executed
**/
event RebalanceStableBorrowRate(
address indexed reserve,
address indexed user
);
/**
* @dev Emitted on flashLoan()
* @param target The address of the flash loan receiver contract
* @param initiator The address initiating the flash loan
* @param asset The address of the asset being flash borrowed
* @param amount The amount flash borrowed
* @param premium The fee flash borrowed
* @param referralCode The referral code used
**/
event FlashLoan(
address indexed target,
address indexed initiator,
address indexed asset,
uint256 amount,
uint256 premium,
uint16 referralCode
);
/**
* @dev Emitted when the pause is triggered.
*/
event Paused();
/**
* @dev Emitted when the pause is lifted.
*/
event Unpaused();
/**
* @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via
* LendingPoolCollateral manager using a DELEGATECALL
* This allows to have the events in the generated ABI for LendingPool.
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param liquidatedCollateralAmount The amount of collateral received by the liiquidator
* @param liquidator The address of the liquidator
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
event LiquidationCall(
address indexed collateralAsset,
address indexed debtAsset,
address indexed user,
uint256 debtToCover,
uint256 liquidatedCollateralAmount,
address liquidator,
bool receiveAToken
);
/**
* @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared
* in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,
* the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it
* gets added to the LendingPool ABI
* @param reserve The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param stableBorrowRate The new stable borrow rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already deposited enough collateral, or he was given enough allowance by a credit delegator on the
* corresponding debt token (StableDebtToken or VariableDebtToken)
* - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
* and 100 stable/variable debt tokens, depending on the `interestRateMode`
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
* @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint16 referralCode,
address onBehalfOf
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
* @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
* @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
* @return The final amount repaid
**/
function repay(
address asset,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external returns (uint256);
/**
* @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa
* @param asset The address of the underlying asset borrowed
* @param rateMode The rate mode that the user wants to swap to
**/
function swapBorrowRateMode(address asset, uint256 rateMode) external;
/**
* @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.
* - Users can be rebalanced if the following conditions are satisfied:
* 1. Usage ratio is above 95%
* 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been
* borrowed at a stable rate and depositors are not earning enough
* @param asset The address of the underlying asset borrowed
* @param user The address of the user to be rebalanced
**/
function rebalanceStableBorrowRate(address asset, address user) external;
/**
* @dev Allows depositors to enable/disable a specific deposited asset as collateral
* @param asset The address of the underlying asset deposited
* @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise
**/
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral)
external;
/**
* @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
* - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
function liquidationCall(
address collateralAsset,
address debtAsset,
address user,
uint256 debtToCover,
bool receiveAToken
) external;
/**
* @dev Allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned.
* IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.
* For further details please visit https://developers.aave.com
* @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface
* @param assets The addresses of the assets being flash-borrowed
* @param amounts The amounts amounts being flash-borrowed
* @param modes Types of the debt to open if the flash loan is not returned:
* 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
* 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2
* @param params Variadic packed params to pass to the receiver as extra information
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
/**
* @dev Returns the user account data across all the reserves
* @param user The address of the user
* @return totalCollateralETH the total collateral in ETH of the user
* @return totalDebtETH the total debt in ETH of the user
* @return availableBorrowsETH the borrowing power left of the user
* @return currentLiquidationThreshold the liquidation threshold of the user
* @return ltv the loan to value of the user
* @return healthFactor the current health factor of the user
**/
function getUserAccountData(address user)
external
view
returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
function initReserve(
address reserve,
address aTokenAddress,
address stableDebtAddress,
address variableDebtAddress,
address interestRateStrategyAddress
) external;
function setReserveInterestRateStrategyAddress(
address reserve,
address rateStrategyAddress
) external;
function setConfiguration(address reserve, uint256 configuration) external;
/**
* @dev Returns the configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The configuration of the reserve
**/
function getConfiguration(address asset)
external
view
returns (DataTypes.ReserveConfigurationMap memory);
/**
* @dev Returns the configuration of the user across all the reserves
* @param user The user address
* @return The configuration of the user
**/
function getUserConfiguration(address user)
external
view
returns (DataTypes.UserConfigurationMap memory);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset)
external
view
returns (uint256);
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset)
external
view
returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset)
external
view
returns (DataTypes.ReserveData memory);
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromAfter,
uint256 balanceToBefore
) external;
function getReservesList() external view returns (address[] memory);
function getAddressesProvider()
external
view
returns (ILendingPoolAddressesProvider);
function setPause(bool val) external;
function paused() external view returns (bool);
}
// Part: IProtocolDataProvider
interface IProtocolDataProvider {
struct TokenData {
string symbol;
address tokenAddress;
}
function ADDRESSES_PROVIDER()
external
view
returns (ILendingPoolAddressesProvider);
function getAllReservesTokens() external view returns (TokenData[] memory);
function getAllATokens() external view returns (TokenData[] memory);
function getReserveConfigurationData(address asset)
external
view
returns (
uint256 decimals,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
uint256 reserveFactor,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive,
bool isFrozen
);
function getReserveData(address asset)
external
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
function getUserReserveData(address asset, address user)
external
view
returns (
uint256 currentATokenBalance,
uint256 currentStableDebt,
uint256 currentVariableDebt,
uint256 principalStableDebt,
uint256 scaledVariableDebt,
uint256 stableBorrowRate,
uint256 liquidityRate,
uint40 stableRateLastUpdated,
bool usageAsCollateralEnabled
);
function getReserveTokensAddresses(address asset)
external
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
}
// Part: ISwapRouter
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params)
external
payable
returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params)
external
payable
returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params)
external
payable
returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params)
external
payable
returns (uint256 amountIn);
}
// Part: IVariableDebtToken
/**
* @title IVariableDebtToken
* @author Aave
* @notice Defines the basic interface for a variable debt token.
**/
interface IVariableDebtToken is IERC20, IScaledBalanceToken {
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param onBehalfOf The address of the user on which behalf minting has been performed
* @param value The amount to be minted
* @param index The last index of the reserve
**/
event Mint(
address indexed from,
address indexed onBehalfOf,
uint256 value,
uint256 index
);
/**
* @dev Mints debt token to the `onBehalfOf` address
* @param user The address receiving the borrowed underlying, being the delegatee in case
* of credit delegate, or same as `onBehalfOf` otherwise
* @param onBehalfOf The address receiving the debt tokens
* @param amount The amount of debt being minted
* @param index The variable debt index of the reserve
* @return `true` if the the previous balance of the user is 0
**/
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted when variable debt is burnt
* @param user The user which debt has been burned
* @param amount The amount of debt being burned
* @param index The index of the user
**/
event Burn(address indexed user, uint256 amount, uint256 index);
/**
* @dev Burns user variable debt
* @param user The user which debt is burnt
* @param index The variable debt index of the reserve
**/
function burn(
address user,
uint256 amount,
uint256 index
) external;
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController()
external
view
returns (IAaveIncentivesController);
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: yearn/[email protected]/VaultAPI
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: IInitializableAToken
/**
* @title IInitializableAToken
* @notice Interface for the initialize function on AToken
* @author Aave
**/
interface IInitializableAToken {
/**
* @dev Emitted when an aToken is initialized
* @param underlyingAsset The address of the underlying asset
* @param pool The address of the associated lending pool
* @param treasury The address of the treasury
* @param incentivesController The address of the incentives controller for this aToken
* @param aTokenDecimals the decimals of the underlying
* @param aTokenName the name of the aToken
* @param aTokenSymbol the symbol of the aToken
* @param params A set of encoded parameters for additional initialization
**/
event Initialized(
address indexed underlyingAsset,
address indexed pool,
address treasury,
address incentivesController,
uint8 aTokenDecimals,
string aTokenName,
string aTokenSymbol,
bytes params
);
/**
* @dev Initializes the aToken
* @param pool The address of the lending pool where this aToken will be used
* @param treasury The address of the Aave treasury, receiving the fees on this aToken
* @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)
* @param incentivesController The smart contract managing potential incentives distribution
* @param aTokenDecimals The decimals of the aToken, same as the underlying asset's
* @param aTokenName The name of the aToken
* @param aTokenSymbol The symbol of the aToken
*/
function initialize(
ILendingPool pool,
address treasury,
address underlyingAsset,
IAaveIncentivesController incentivesController,
uint8 aTokenDecimals,
string calldata aTokenName,
string calldata aTokenSymbol,
bytes calldata params
) external;
}
// Part: yearn/[email protected]/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
// health checks
bool public doHealthCheck;
address public healthCheck;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.4.3";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external view virtual returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external view virtual returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyEmergencyAuthorized() {
require(
msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyVaultManagers() {
require(msg.sender == vault.management() || msg.sender == governance(), "!authorized");
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
* @param _strategist The address to assign as `strategist`.
* The strategist is able to change the reward address
* @param _rewards The address to use for pulling rewards.
* @param _keeper The adddress of the _keeper. _keeper
* can harvest and tend a strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
function setHealthCheck(address _healthCheck) external onlyVaultManagers {
healthCheck = _healthCheck;
}
function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers {
doHealthCheck = _doHealthCheck;
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate conversion from `_amtInWei` (denominated in wei)
* to `want` (using the native decimal characteristics of `want`).
* @dev
* Care must be taken when working with decimals to assure that the conversion
* is compatible. As an example:
*
* given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals),
* with USDC/ETH = 1800, this should give back 1800000000 (180 USDC)
*
* @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want`
* @return The amount in `want` of `_amtInEth` converted to `want`
**/
function ethToWant(uint256 _amtInWei) public view virtual returns (uint256);
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public view virtual returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* Liquidate everything and returns the amount that got freed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*/
function liquidateAllPositions() internal virtual returns (uint256 _amountFreed);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei).
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
// If your implementation uses the cost of the call in want, you can
// use uint256 callCost = ethToWant(callCostInWei);
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei).
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) {
uint256 callCost = ethToWant(callCostInWei);
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 amountFreed = liquidateAllPositions();
if (amountFreed < debtOutstanding) {
loss = debtOutstanding.sub(amountFreed);
} else if (amountFreed > debtOutstanding) {
profit = amountFreed.sub(debtOutstanding);
}
debtPayment = debtOutstanding.sub(loss);
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
// call healthCheck contract
if (doHealthCheck && healthCheck != address(0)) {
require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck");
} else {
doHealthCheck = true;
}
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* The migration process should be carefully performed to make sure all
* the assets are migrated to the new address, which should have never
* interacted with the vault before.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault));
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyEmergencyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
* ```
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
* ```
*/
function protectedTokens() internal view virtual returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// Part: IAToken
interface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken {
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param value The amount being
* @param index The new liquidity index of the reserve
**/
event Mint(address indexed from, uint256 value, uint256 index);
/**
* @dev Mints `amount` aTokens to `user`
* @param user The address receiving the minted tokens
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
* @return `true` if the the previous balance of the user was 0
*/
function mint(
address user,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted after aTokens are burned
* @param from The owner of the aTokens, getting them burned
* @param target The address that will receive the underlying
* @param value The amount being burned
* @param index The new liquidity index of the reserve
**/
event Burn(
address indexed from,
address indexed target,
uint256 value,
uint256 index
);
/**
* @dev Emitted during the transfer action
* @param from The user whose tokens are being transferred
* @param to The recipient
* @param value The amount being transferred
* @param index The new liquidity index of the reserve
**/
event BalanceTransfer(
address indexed from,
address indexed to,
uint256 value,
uint256 index
);
/**
* @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`
* @param user The owner of the aTokens, getting them burned
* @param receiverOfUnderlying The address that will receive the underlying
* @param amount The amount being burned
* @param index The new liquidity index of the reserve
**/
function burn(
address user,
address receiverOfUnderlying,
uint256 amount,
uint256 index
) external;
/**
* @dev Mints aTokens to the reserve treasury
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
*/
function mintToTreasury(uint256 amount, uint256 index) external;
/**
* @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken
* @param from The address getting liquidated, current owner of the aTokens
* @param to The recipient
* @param value The amount of tokens getting transferred
**/
function transferOnLiquidation(
address from,
address to,
uint256 value
) external;
/**
* @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer
* assets in borrow(), withdraw() and flashLoan()
* @param user The recipient of the underlying
* @param amount The amount getting transferred
* @return The amount transferred
**/
function transferUnderlyingTo(address user, uint256 amount)
external
returns (uint256);
/**
* @dev Invoked to execute actions on the aToken side after a repayment.
* @param user The user executing the repayment
* @param amount The amount getting repaid
**/
function handleRepayment(address user, uint256 amount) external;
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController()
external
view
returns (IAaveIncentivesController);
/**
* @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH)
**/
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
}
// Part: yearn/[email protected]/BaseStrategyInitializable
abstract contract BaseStrategyInitializable is BaseStrategy {
bool public isOriginal = true;
event Cloned(address indexed clone);
constructor(address _vault) public BaseStrategy(_vault) {}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external virtual {
_initialize(_vault, _strategist, _rewards, _keeper);
}
function clone(address _vault) external returns (address) {
require(isOriginal, "!clone");
return this.clone(_vault, msg.sender, msg.sender, msg.sender);
}
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
BaseStrategyInitializable(newStrategy).initialize(_vault, _strategist, _rewards, _keeper);
emit Cloned(newStrategy);
}
}
// Part: FlashLoanLib
library FlashLoanLib {
using SafeMath for uint256;
event Leverage(
uint256 amountRequested,
uint256 amountGiven,
bool deficit,
address flashLoan
);
address public constant SOLO = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
uint256 private constant collatRatioETH = 0.79 ether;
uint256 private constant COLLAT_RATIO_PRECISION = 1 ether;
address private constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
IAToken public constant aWeth =
IAToken(0x030bA81f1c18d280636F32af80b9AAd02Cf0854e);
IProtocolDataProvider private constant protocolDataProvider =
IProtocolDataProvider(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d);
ILendingPool private constant lendingPool =
ILendingPool(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9);
// Aave's referral code
uint16 private constant referral = 0;
function doDyDxFlashLoan(
bool deficit,
uint256 amountDesired,
address token
) public returns (uint256 amount) {
if (amountDesired == 0) {
return 0;
}
amount = amountDesired;
ISoloMargin solo = ISoloMargin(SOLO);
// calculate amount of ETH we need
uint256 requiredETH;
{
requiredETH = _toETH(amount, token).mul(COLLAT_RATIO_PRECISION).div(
collatRatioETH
);
uint256 dxdyLiquidity = IERC20(weth).balanceOf(address(solo));
if (requiredETH > dxdyLiquidity) {
requiredETH = dxdyLiquidity;
// NOTE: if we cap amountETH, we reduce amountToken we are taking too
amount = _fromETH(requiredETH, token).mul(collatRatioETH).div(
1 ether
);
}
}
// Array of actions to be done during FlashLoan
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
// 1. Take FlashLoan
operations[0] = _getWithdrawAction(0, requiredETH); // hardcoded market ID to 0 (ETH)
// 2. Encode arguments of functions and create action for calling it
bytes memory data = abi.encode(deficit, amount);
// This call will:
// supply ETH to Aave
// borrow desired Token from Aave
// do stuff with Token
// repay desired Token to Aave
// withdraw ETH from Aave
operations[1] = _getCallAction(data);
// 3. Repay FlashLoan
operations[2] = _getDepositAction(0, requiredETH.add(2));
// Create Account Info
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
solo.operate(accountInfos, operations);
emit Leverage(amountDesired, requiredETH, deficit, address(solo));
return amount; // we need to return the amount of Token we have changed our position in
}
function loanLogic(
bool deficit,
uint256 amount,
address want
) public {
uint256 wethBal = IERC20(weth).balanceOf(address(this));
ILendingPool lp = lendingPool;
// 1. Deposit WETH in Aave as collateral
lp.deposit(weth, wethBal, address(this), referral);
if (deficit) {
// 2a. if in deficit withdraw amount and repay it
lp.withdraw(want, amount, address(this));
lp.repay(want, amount, 2, address(this));
} else {
// 2b. if levering up borrow and deposit
lp.borrow(want, amount, 2, 0, address(this));
lp.deposit(
want,
IERC20(want).balanceOf(address(this)),
address(this),
referral
);
}
// 3. Withdraw WETH
lp.withdraw(weth, wethBal, address(this));
}
function _getAccountInfo() internal view returns (Account.Info memory) {
return Account.Info({owner: address(this), number: 1});
}
function _getWithdrawAction(uint256 marketId, uint256 amount)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: 0
}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint256 marketId, uint256 amount)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
function _priceOracle() internal view returns (IPriceOracle) {
return
IPriceOracle(
protocolDataProvider.ADDRESSES_PROVIDER().getPriceOracle()
);
}
function _toETH(uint256 _amount, address asset)
internal
view
returns (uint256)
{
if (
_amount == 0 ||
_amount == type(uint256).max ||
address(asset) == address(weth) // 1:1 change
) {
return _amount;
}
return
_amount.mul(_priceOracle().getAssetPrice(asset)).div(
uint256(10)**uint256(IOptionalERC20(asset).decimals())
);
}
function _fromETH(uint256 _amount, address asset)
internal
view
returns (uint256)
{
if (
_amount == 0 ||
_amount == type(uint256).max ||
address(asset) == address(weth) // 1:1 change
) {
return _amount;
}
return
_amount
.mul(uint256(10)**uint256(IOptionalERC20(asset).decimals()))
.div(_priceOracle().getAssetPrice(asset));
}
}
// File: Strategy.sol
contract Strategy is BaseStrategyInitializable, ICallee {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// AAVE protocol address
IProtocolDataProvider private constant protocolDataProvider =
IProtocolDataProvider(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d);
IAaveIncentivesController private constant incentivesController =
IAaveIncentivesController(0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5);
ILendingPool private constant lendingPool =
ILendingPool(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9);
// Token addresses
address private constant aave = 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9;
IStakedAave private constant stkAave =
IStakedAave(0x4da27a545c0c5B758a6BA100e3a049001de870f5);
address private constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// Supply and borrow tokens
IAToken public aToken;
IVariableDebtToken public debtToken;
// SWAP routers
IUni private constant V2ROUTER =
IUni(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
ISwapRouter private constant V3ROUTER =
ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564);
// OPS State Variables
uint256 private constant DEFAULT_COLLAT_TARGET_MARGIN = 0.02 ether;
uint256 private constant DEFAULT_COLLAT_MAX_MARGIN = 0.005 ether;
uint256 private constant LIQUIDATION_WARNING_THRESHOLD = 0.01 ether;
uint256 public maxBorrowCollatRatio; // The maximum the aave protocol will let us borrow
uint256 public targetCollatRatio; // The LTV we are levering up to
uint256 public maxCollatRatio; // Closest to liquidation we'll risk
uint8 public maxIterations = 6;
bool public isDyDxActive = true;
uint256 public minWant = 100;
uint256 public minRatio = 0.005 ether;
uint256 public minRewardToSell = 1e15;
bool public sellStkAave = true;
bool public cooldownStkAave = false;
bool public useUniV3 = false; // only applied to aave => want, stkAave => aave always uses v3
uint256 public maxStkAavePriceImpactBps = 1000;
uint24 public stkAaveToAaveSwapFee = 10000;
uint24 public aaveToWethSwapFee = 3000;
uint24 public wethToWantSwapFee = 3000;
uint16 private constant referral = 0; // Aave's referral code
bool private alreadyAdjusted = false; // Signal whether a position adjust was done in prepareReturn
uint256 private constant MAX_BPS = 1e4;
uint256 private constant BPS_WAD_RATIO = 1e14;
uint256 private constant COLLATERAL_RATIO_PRECISION = 1 ether;
uint256 private constant PESSIMISM_FACTOR = 1000;
uint256 private DECIMALS;
constructor(address _vault) public BaseStrategyInitializable(_vault) {
_initializeThis();
}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external override {
_initialize(_vault, _strategist, _rewards, _keeper);
_initializeThis();
}
function _initializeThis() internal {
require(address(aToken) == address(0));
// initialize operational state
maxIterations = 6;
isDyDxActive = true;
// mins
minWant = 100;
minRatio = 0.005 ether;
minRewardToSell = 1e15;
// reward params
sellStkAave = true;
cooldownStkAave = false;
useUniV3 = false;
maxStkAavePriceImpactBps = 1000;
stkAaveToAaveSwapFee = 10000;
aaveToWethSwapFee = 3000;
wethToWantSwapFee = 3000;
// Set aave tokens
(address _aToken, , address _debtToken) =
protocolDataProvider.getReserveTokensAddresses(address(want));
aToken = IAToken(_aToken);
debtToken = IVariableDebtToken(_debtToken);
// Let collateral targets
(, uint256 ltv, uint256 liquidationThreshold, , , , , , , ) =
protocolDataProvider.getReserveConfigurationData(address(want));
liquidationThreshold = liquidationThreshold.mul(BPS_WAD_RATIO); // convert bps to wad
targetCollatRatio = liquidationThreshold.sub(
DEFAULT_COLLAT_TARGET_MARGIN
);
maxCollatRatio = liquidationThreshold.sub(DEFAULT_COLLAT_MAX_MARGIN);
maxBorrowCollatRatio = ltv.mul(BPS_WAD_RATIO).sub(
DEFAULT_COLLAT_MAX_MARGIN
);
DECIMALS = 10**vault.decimals();
// approve spend aave spend
approveMaxSpend(address(want), address(lendingPool));
approveMaxSpend(address(aToken), address(lendingPool));
// approve flashloan spend
approveMaxSpend(weth, address(lendingPool));
approveMaxSpend(weth, FlashLoanLib.SOLO);
// approve swap router spend
approveMaxSpend(address(stkAave), address(V3ROUTER));
approveMaxSpend(aave, address(V2ROUTER));
approveMaxSpend(aave, address(V3ROUTER));
}
// SETTERS
function setCollateralTargets(
uint256 _targetCollatRatio,
uint256 _maxCollatRatio,
uint256 _maxBorrowCollatRatio
) external onlyVaultManagers {
(, uint256 ltv, uint256 liquidationThreshold, , , , , , , ) =
protocolDataProvider.getReserveConfigurationData(address(want));
// convert bps to wad
ltv = ltv.mul(BPS_WAD_RATIO);
liquidationThreshold = liquidationThreshold.mul(BPS_WAD_RATIO);
require(_targetCollatRatio < liquidationThreshold);
require(_maxCollatRatio < liquidationThreshold);
require(_targetCollatRatio < _maxCollatRatio);
require(_maxBorrowCollatRatio < ltv);
targetCollatRatio = _targetCollatRatio;
maxCollatRatio = _maxCollatRatio;
maxBorrowCollatRatio = _maxBorrowCollatRatio;
}
function setIsDyDxActive(bool _isDyDxActive) external onlyVaultManagers {
isDyDxActive = _isDyDxActive;
}
function setMinsAndMaxs(
uint256 _minWant,
uint256 _minRatio,
uint8 _maxIterations
) external onlyVaultManagers {
require(_minRatio < maxBorrowCollatRatio);
require(_maxIterations > 0 && _maxIterations < 16);
minWant = _minWant;
minRatio = _minRatio;
maxIterations = _maxIterations;
}
function setRewardBehavior(
bool _sellStkAave,
bool _cooldownStkAave,
bool _useUniV3,
uint256 _minRewardToSell,
uint256 _maxStkAavePriceImpactBps,
uint24 _stkAaveToAaveSwapFee,
uint24 _aaveToWethSwapFee,
uint24 _wethToWantSwapFee
) external onlyVaultManagers {
require(_maxStkAavePriceImpactBps <= MAX_BPS);
sellStkAave = _sellStkAave;
cooldownStkAave = _cooldownStkAave;
useUniV3 = _useUniV3;
minRewardToSell = _minRewardToSell;
maxStkAavePriceImpactBps = _maxStkAavePriceImpactBps;
stkAaveToAaveSwapFee = _stkAaveToAaveSwapFee;
aaveToWethSwapFee = _aaveToWethSwapFee;
wethToWantSwapFee = _wethToWantSwapFee;
}
function name() external view override returns (string memory) {
return "StrategyGenLevAAVE";
}
function estimatedTotalAssets() public view override returns (uint256) {
uint256 balanceExcludingRewards =
balanceOfWant().add(getCurrentSupply());
// if we don't have a position, don't worry about rewards
if (balanceExcludingRewards < minWant) {
return balanceExcludingRewards;
}
uint256 rewards =
estimatedRewardsInWant().mul(MAX_BPS.sub(PESSIMISM_FACTOR)).div(
MAX_BPS
);
return balanceExcludingRewards.add(rewards);
}
function estimatedRewardsInWant() public view returns (uint256) {
uint256 aaveBalance = balanceOfAave();
uint256 stkAaveBalance = balanceOfStkAave();
uint256 pendingRewards =
incentivesController.getRewardsBalance(
getAaveAssets(),
address(this)
);
uint256 stkAaveDiscountFactor = MAX_BPS.sub(maxStkAavePriceImpactBps);
uint256 combinedStkAave =
pendingRewards.add(stkAaveBalance).mul(stkAaveDiscountFactor).div(
MAX_BPS
);
return tokenToWant(aave, aaveBalance.add(combinedStkAave));
}
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
// claim & sell rewards
_claimAndSellRewards();
// account for profit / losses
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
// Assets immediately convertable to want only
uint256 supply = getCurrentSupply();
uint256 totalAssets = balanceOfWant().add(supply);
if (totalDebt > totalAssets) {
// we have losses
_loss = totalDebt.sub(totalAssets);
} else {
// we have profit
_profit = totalAssets.sub(totalDebt);
}
// free funds to repay debt + profit to the strategy
uint256 amountAvailable = balanceOfWant();
uint256 amountRequired = _debtOutstanding.add(_profit);
if (amountRequired > amountAvailable) {
// we need to free funds
// we dismiss losses here, they cannot be generated from withdrawal
// but it is possible for the strategy to unwind full position
(amountAvailable, ) = liquidatePosition(amountRequired);
// Don't do a redundant adjustment in adjustPosition
alreadyAdjusted = true;
if (amountAvailable >= amountRequired) {
_debtPayment = _debtOutstanding;
// profit remains unchanged unless there is not enough to pay it
if (amountRequired.sub(_debtPayment) < _profit) {
_profit = amountRequired.sub(_debtPayment);
}
} else {
// we were not able to free enough funds
if (amountAvailable < _debtOutstanding) {
// available funds are lower than the repayment that we need to do
_profit = 0;
_debtPayment = amountAvailable;
// we dont report losses here as the strategy might not be able to return in this harvest
// but it will still be there for the next harvest
} else {
// NOTE: amountRequired is always equal or greater than _debtOutstanding
// important to use amountRequired just in case amountAvailable is > amountAvailable
_debtPayment = _debtOutstanding;
_profit = amountAvailable.sub(_debtPayment);
}
}
} else {
_debtPayment = _debtOutstanding;
// profit remains unchanged unless there is not enough to pay it
if (amountRequired.sub(_debtPayment) < _profit) {
_profit = amountRequired.sub(_debtPayment);
}
}
}
function adjustPosition(uint256 _debtOutstanding) internal override {
if (alreadyAdjusted) {
alreadyAdjusted = false; // reset for next time
return;
}
uint256 wantBalance = balanceOfWant();
// deposit available want as collateral
if (
wantBalance > _debtOutstanding &&
wantBalance.sub(_debtOutstanding) > minWant
) {
_depositCollateral(wantBalance.sub(_debtOutstanding));
// we update the value
wantBalance = balanceOfWant();
}
// check current position
uint256 currentCollatRatio = getCurrentCollatRatio();
// Either we need to free some funds OR we want to be max levered
if (_debtOutstanding > wantBalance) {
// we should free funds
uint256 amountRequired = _debtOutstanding.sub(wantBalance);
// NOTE: vault will take free funds during the next harvest
_freeFunds(amountRequired);
} else if (currentCollatRatio < targetCollatRatio) {
// we should lever up
if (targetCollatRatio.sub(currentCollatRatio) > minRatio) {
// we only act on relevant differences
_leverMax();
}
} else if (currentCollatRatio > targetCollatRatio) {
if (currentCollatRatio.sub(targetCollatRatio) > minRatio) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 newBorrow =
getBorrowFromSupply(
deposits.sub(borrows),
targetCollatRatio
);
_leverDownTo(newBorrow, borrows);
}
}
}
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
// NOTE: Maintain invariant `want.balanceOf(this) >= _liquidatedAmount`
// NOTE: Maintain invariant `_liquidatedAmount + _loss <= _amountNeeded`
uint256 wantBalance = balanceOfWant();
if (wantBalance > _amountNeeded) {
// if there is enough free want, let's use it
return (_amountNeeded, 0);
}
// we need to free funds
uint256 amountRequired = _amountNeeded.sub(wantBalance);
_freeFunds(amountRequired);
uint256 freeAssets = balanceOfWant();
if (_amountNeeded > freeAssets) {
_liquidatedAmount = freeAssets;
_loss = _amountNeeded.sub(freeAssets);
} else {
_liquidatedAmount = _amountNeeded;
}
}
function tendTrigger(uint256 gasCost) public view override returns (bool) {
if (harvestTrigger(gasCost)) {
//harvest takes priority
return false;
}
// pull the liquidation liquidationThreshold from aave to be extra safu
(, , uint256 liquidationThreshold, , , , , , , ) =
protocolDataProvider.getReserveConfigurationData(address(want));
// convert bps to wad
liquidationThreshold = liquidationThreshold.mul(BPS_WAD_RATIO);
uint256 currentCollatRatio = getCurrentCollatRatio();
if (currentCollatRatio >= liquidationThreshold) {
return true;
}
return (liquidationThreshold.sub(currentCollatRatio) <=
LIQUIDATION_WARNING_THRESHOLD);
}
function liquidateAllPositions()
internal
override
returns (uint256 _amountFreed)
{
(_amountFreed, ) = liquidatePosition(type(uint256).max);
}
function prepareMigration(address _newStrategy) internal override {
require(getCurrentSupply() < minWant);
}
function protectedTokens()
internal
view
override
returns (address[] memory)
{}
//emergency function that we can use to deleverage manually if something is broken
function manualDeleverage(uint256 amount) external onlyVaultManagers {
_withdrawCollateral(amount);
_repayWant(amount);
}
//emergency function that we can use to deleverage manually if something is broken
function manualReleaseWant(uint256 amount) external onlyVaultManagers {
_withdrawCollateral(amount);
}
// emergency function that we can use to sell rewards if something is broken
function manualClaimAndSellRewards() external onlyVaultManagers {
_claimAndSellRewards();
}
// INTERNAL ACTIONS
function _claimAndSellRewards() internal returns (uint256) {
uint256 stkAaveBalance = balanceOfStkAave();
uint8 cooldownStatus = stkAaveBalance == 0 ? 0 : _checkCooldown(); // don't check status if we have no stkAave
// If it's the claim period claim
if (stkAaveBalance > 0 && cooldownStatus == 1) {
// redeem AAVE from stkAave
stkAave.claimRewards(address(this), type(uint256).max);
stkAave.redeem(address(this), stkAaveBalance);
}
// claim stkAave from lending and borrowing, this will reset the cooldown
incentivesController.claimRewards(
getAaveAssets(),
type(uint256).max,
address(this)
);
stkAaveBalance = balanceOfStkAave();
// request start of cooldown period, if there's no cooldown in progress
if (cooldownStkAave && stkAaveBalance > 0 && cooldownStatus == 0) {
stkAave.cooldown();
}
// Always keep 1 wei to get around cooldown clear
if (sellStkAave && stkAaveBalance >= minRewardToSell.add(1)) {
uint256 minAAVEOut =
stkAaveBalance.mul(MAX_BPS.sub(maxStkAavePriceImpactBps)).div(
MAX_BPS
);
_sellSTKAAVEToAAVE(stkAaveBalance.sub(1), minAAVEOut);
}
// sell AAVE for want
uint256 aaveBalance = balanceOfAave();
if (aaveBalance >= minRewardToSell) {
_sellAAVEForWant(aaveBalance, 0);
}
}
function _freeFunds(uint256 amountToFree) internal returns (uint256) {
if (amountToFree == 0) return 0;
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 realAssets = deposits.sub(borrows);
uint256 amountRequired = Math.min(amountToFree, realAssets);
uint256 newSupply = realAssets.sub(amountRequired);
uint256 newBorrow = getBorrowFromSupply(newSupply, targetCollatRatio);
// repay required amount
_leverDownTo(newBorrow, borrows);
return balanceOfWant();
}
function _leverMax() internal {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
// NOTE: decimals should cancel out
uint256 realSupply = deposits.sub(borrows);
uint256 newBorrow = getBorrowFromSupply(realSupply, targetCollatRatio);
uint256 totalAmountToBorrow = newBorrow.sub(borrows);
if (isDyDxActive) {
// The best approach is to lever up using regular method, then finish with flash loan
totalAmountToBorrow = totalAmountToBorrow.sub(
_leverUpStep(totalAmountToBorrow)
);
if (totalAmountToBorrow > minWant) {
totalAmountToBorrow = totalAmountToBorrow.sub(
_leverUpFlashLoan(totalAmountToBorrow)
);
}
} else {
for (
uint8 i = 0;
i < maxIterations && totalAmountToBorrow > minWant;
i++
) {
totalAmountToBorrow = totalAmountToBorrow.sub(
_leverUpStep(totalAmountToBorrow)
);
}
}
}
function _leverUpFlashLoan(uint256 amount) internal returns (uint256) {
return FlashLoanLib.doDyDxFlashLoan(false, amount, address(want));
}
function _leverUpStep(uint256 amount) internal returns (uint256) {
if (amount == 0) {
return 0;
}
uint256 wantBalance = balanceOfWant();
// calculate how much borrow can I take
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 canBorrow =
getBorrowFromDeposit(
deposits.add(wantBalance),
maxBorrowCollatRatio
);
if (canBorrow <= borrows) {
return 0;
}
canBorrow = canBorrow.sub(borrows);
if (canBorrow < amount) {
amount = canBorrow;
}
// deposit available want as collateral
_depositCollateral(wantBalance);
// borrow available amount
_borrowWant(amount);
return amount;
}
function _leverDownTo(uint256 newAmountBorrowed, uint256 currentBorrowed)
internal
returns (uint256)
{
if (newAmountBorrowed >= currentBorrowed) {
// we don't need to repay
return 0;
}
uint256 totalRepayAmount = currentBorrowed.sub(newAmountBorrowed);
if (isDyDxActive) {
totalRepayAmount = totalRepayAmount.sub(
_leverDownFlashLoan(totalRepayAmount)
);
_withdrawExcessCollateral();
}
for (
uint8 i = 0;
i < maxIterations && totalRepayAmount > minWant;
i++
) {
uint256 toRepay = totalRepayAmount;
uint256 wantBalance = balanceOfWant();
if (toRepay > wantBalance) {
toRepay = wantBalance;
}
uint256 repaid = _repayWant(toRepay);
totalRepayAmount = totalRepayAmount.sub(repaid);
// withdraw collateral
_withdrawExcessCollateral();
}
// deposit back to get targetCollatRatio (we always need to leave this in this ratio)
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 targetDeposit =
getDepositFromBorrow(borrows, targetCollatRatio);
if (targetDeposit > deposits) {
uint256 toDeposit = targetDeposit.sub(deposits);
if (toDeposit > minWant) {
_depositCollateral(Math.min(toDeposit, balanceOfWant()));
}
}
}
function _leverDownFlashLoan(uint256 amount) internal returns (uint256) {
if (amount <= minWant) return 0;
(, uint256 borrows) = getCurrentPosition();
if (amount > borrows) {
amount = borrows;
}
return FlashLoanLib.doDyDxFlashLoan(true, amount, address(want));
}
function _withdrawExcessCollateral() internal returns (uint256 amount) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 theoDeposits = getDepositFromBorrow(borrows, maxCollatRatio);
if (deposits > theoDeposits) {
uint256 toWithdraw = deposits.sub(theoDeposits);
return _withdrawCollateral(toWithdraw);
}
}
function _depositCollateral(uint256 amount) internal returns (uint256) {
if (amount == 0) return 0;
lendingPool.deposit(address(want), amount, address(this), referral);
return amount;
}
function _withdrawCollateral(uint256 amount) internal returns (uint256) {
if (amount == 0) return 0;
lendingPool.withdraw(address(want), amount, address(this));
return amount;
}
function _repayWant(uint256 amount) internal returns (uint256) {
if (amount == 0) return 0;
return lendingPool.repay(address(want), amount, 2, address(this));
}
function _borrowWant(uint256 amount) internal returns (uint256) {
if (amount == 0) return 0;
lendingPool.borrow(address(want), amount, 2, referral, address(this));
return amount;
}
// INTERNAL VIEWS
function balanceOfWant() internal view returns (uint256) {
return want.balanceOf(address(this));
}
function balanceOfAToken() internal view returns (uint256) {
return aToken.balanceOf(address(this));
}
function balanceOfDebtToken() internal view returns (uint256) {
return debtToken.balanceOf(address(this));
}
function balanceOfAave() internal view returns (uint256) {
return IERC20(aave).balanceOf(address(this));
}
function balanceOfStkAave() internal view returns (uint256) {
return IERC20(address(stkAave)).balanceOf(address(this));
}
// Flashloan callback function
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public override {
(bool deficit, uint256 amount) = abi.decode(data, (bool, uint256));
require(msg.sender == FlashLoanLib.SOLO);
require(sender == address(this));
FlashLoanLib.loanLogic(deficit, amount, address(want));
}
function getCurrentPosition()
public
view
returns (uint256 deposits, uint256 borrows)
{
deposits = balanceOfAToken();
borrows = balanceOfDebtToken();
}
function getCurrentCollatRatio()
public
view
returns (uint256 currentCollatRatio)
{
(uint256 deposits, uint256 borrows) = getCurrentPosition();
if (deposits > 0) {
currentCollatRatio = borrows.mul(COLLATERAL_RATIO_PRECISION).div(
deposits
);
}
}
function getCurrentSupply() public view returns (uint256) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
return deposits.sub(borrows);
}
// conversions
function tokenToWant(address token, uint256 amount)
internal
view
returns (uint256)
{
if (amount == 0 || address(want) == token) {
return amount;
}
uint256[] memory amounts =
IUni(V2ROUTER).getAmountsOut(
amount,
getTokenOutPathV2(token, address(want))
);
return amounts[amounts.length - 1];
}
function ethToWant(uint256 _amtInWei)
public
view
override
returns (uint256)
{
return tokenToWant(weth, _amtInWei);
}
// returns cooldown status
// 0 = no cooldown or past withdraw period
// 1 = claim period
// 2 = cooldown initiated, future claim period
function _checkCooldown() internal view returns (uint8) {
uint256 cooldownStartTimestamp =
IStakedAave(stkAave).stakersCooldowns(address(this));
uint256 COOLDOWN_SECONDS = IStakedAave(stkAave).COOLDOWN_SECONDS();
uint256 UNSTAKE_WINDOW = IStakedAave(stkAave).UNSTAKE_WINDOW();
uint256 nextClaimStartTimestamp =
cooldownStartTimestamp.add(COOLDOWN_SECONDS);
if (cooldownStartTimestamp == 0) {
return 0;
}
if (
block.timestamp > nextClaimStartTimestamp &&
block.timestamp <= nextClaimStartTimestamp.add(UNSTAKE_WINDOW)
) {
return 1;
}
if (block.timestamp < nextClaimStartTimestamp) {
return 2;
}
}
function getTokenOutPathV2(address _token_in, address _token_out)
internal
pure
returns (address[] memory _path)
{
bool is_weth =
_token_in == address(weth) || _token_out == address(weth);
_path = new address[](is_weth ? 2 : 3);
_path[0] = _token_in;
if (is_weth) {
_path[1] = _token_out;
} else {
_path[1] = address(weth);
_path[2] = _token_out;
}
}
function getTokenOutPathV3(address _token_in, address _token_out)
internal
view
returns (bytes memory _path)
{
if (address(want) == weth) {
_path = abi.encodePacked(
address(aave),
aaveToWethSwapFee,
address(weth)
);
} else {
_path = abi.encodePacked(
address(aave),
aaveToWethSwapFee,
address(weth),
wethToWantSwapFee,
address(want)
);
}
}
function _sellAAVEForWant(uint256 amountIn, uint256 minOut) internal {
if (amountIn == 0) {
return;
}
if (useUniV3) {
V3ROUTER.exactInput(
ISwapRouter.ExactInputParams(
getTokenOutPathV3(address(aave), address(want)),
address(this),
now,
amountIn,
minOut
)
);
} else {
V2ROUTER.swapExactTokensForTokens(
amountIn,
minOut,
getTokenOutPathV2(address(aave), address(want)),
address(this),
now
);
}
}
function _sellSTKAAVEToAAVE(uint256 amountIn, uint256 minOut) internal {
// Swap Rewards in UNIV3
// NOTE: Unoptimized, can be frontrun and most importantly this pool is low liquidity
V3ROUTER.exactInputSingle(
ISwapRouter.ExactInputSingleParams(
address(stkAave),
address(aave),
stkAaveToAaveSwapFee,
address(this),
now,
amountIn, // wei
minOut,
0
)
);
}
function getAaveAssets() internal view returns (address[] memory assets) {
assets = new address[](2);
assets[0] = address(aToken);
assets[1] = address(debtToken);
}
function getBorrowFromDeposit(uint256 deposit, uint256 collatRatio)
internal
pure
returns (uint256)
{
return deposit.mul(collatRatio).div(COLLATERAL_RATIO_PRECISION);
}
function getDepositFromBorrow(uint256 borrow, uint256 collatRatio)
internal
pure
returns (uint256)
{
return borrow.mul(COLLATERAL_RATIO_PRECISION).div(collatRatio);
}
function getBorrowFromSupply(uint256 supply, uint256 collatRatio)
internal
pure
returns (uint256)
{
return
supply.mul(collatRatio).div(
COLLATERAL_RATIO_PRECISION.sub(collatRatio)
);
}
function approveMaxSpend(address token, address spender) internal {
IERC20(token).safeApprove(spender, type(uint256).max);
}
} | NOTE: if we cap amountETH, we reduce amountToken we are taking too | ) public returns (uint256 amount) {
if (amountDesired == 0) {
return 0;
}
amount = amountDesired;
ISoloMargin solo = ISoloMargin(SOLO);
{
requiredETH = _toETH(amount, token).mul(COLLAT_RATIO_PRECISION).div(
collatRatioETH
);
uint256 dxdyLiquidity = IERC20(weth).balanceOf(address(solo));
if (requiredETH > dxdyLiquidity) {
requiredETH = dxdyLiquidity;
amount = _fromETH(requiredETH, token).mul(collatRatioETH).div(
1 ether
);
}
}
accountInfos[0] = _getAccountInfo();
solo.operate(accountInfos, operations);
emit Leverage(amountDesired, requiredETH, deficit, address(solo));
}
| 219,068 | [
1,
17857,
30,
309,
732,
3523,
3844,
1584,
44,
16,
732,
5459,
3844,
1345,
732,
854,
13763,
4885,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
262,
1071,
1135,
261,
11890,
5034,
3844,
13,
288,
203,
3639,
309,
261,
8949,
25683,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
3639,
3844,
273,
3844,
25683,
31,
203,
3639,
4437,
12854,
9524,
3704,
83,
273,
4437,
12854,
9524,
12,
3584,
1502,
1769,
203,
203,
3639,
288,
203,
5411,
1931,
1584,
44,
273,
389,
869,
1584,
44,
12,
8949,
16,
1147,
2934,
16411,
12,
4935,
12190,
67,
54,
789,
4294,
67,
3670,
26913,
2934,
2892,
12,
203,
7734,
4508,
270,
8541,
1584,
44,
203,
5411,
11272,
203,
203,
5411,
2254,
5034,
6633,
15680,
48,
18988,
24237,
273,
467,
654,
39,
3462,
12,
91,
546,
2934,
12296,
951,
12,
2867,
12,
87,
12854,
10019,
203,
5411,
309,
261,
4718,
1584,
44,
405,
6633,
15680,
48,
18988,
24237,
13,
288,
203,
7734,
1931,
1584,
44,
273,
6633,
15680,
48,
18988,
24237,
31,
203,
7734,
3844,
273,
389,
2080,
1584,
44,
12,
4718,
1584,
44,
16,
1147,
2934,
16411,
12,
1293,
4801,
8541,
1584,
44,
2934,
2892,
12,
203,
10792,
404,
225,
2437,
203,
7734,
11272,
203,
5411,
289,
203,
3639,
289,
203,
203,
203,
203,
203,
3639,
2236,
7655,
63,
20,
65,
273,
389,
588,
3032,
966,
5621,
203,
203,
3639,
3704,
83,
18,
4063,
340,
12,
4631,
7655,
16,
5295,
1769,
203,
203,
3639,
3626,
3519,
5682,
12,
8949,
25683,
16,
1931,
1584,
44,
16,
1652,
335,
305,
16,
1758,
12,
87,
12854,
10019,
203,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0xc5e7301064f123059702b13A74439aCB9009fa72/sources/src/Transfers.sol | @notice Toggle afterTokenTransfers hook. add admin only @param _target target ERC721 contract @param _enabled enable afterTokenTransferHook | function setAfterTokenTransfersEnabled(
address _target,
bool _enabled
) public onlyAdmin(_target) {
afterTokenTransfersHookEnabled[_target] = _enabled;
}
| 1,904,397 | [
1,
17986,
1839,
1345,
1429,
18881,
3953,
18,
527,
3981,
1338,
225,
389,
3299,
1018,
4232,
39,
27,
5340,
6835,
225,
389,
5745,
4237,
1839,
1345,
5912,
5394,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
444,
4436,
1345,
1429,
18881,
1526,
12,
203,
3639,
1758,
389,
3299,
16,
203,
3639,
1426,
389,
5745,
203,
565,
262,
1071,
1338,
4446,
24899,
3299,
13,
288,
203,
3639,
1839,
1345,
1429,
18881,
5394,
1526,
63,
67,
3299,
65,
273,
389,
5745,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2022-01-25
*/
// Sources flattened with hardhat v2.6.8 https://hardhat.org
// SPDX-License-Identifier: MIT
// File @openzeppelin/contracts/utils/[email protected]
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/introspection/[email protected]
pragma solidity ^0.7.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/token/ERC721/[email protected]
pragma solidity ^0.7.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/[email protected]
pragma solidity ^0.7.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/[email protected]
pragma solidity ^0.7.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.7.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/introspection/[email protected]
pragma solidity ^0.7.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity ^0.7.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;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.7.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// 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(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// 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));
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.7.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry 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.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.7.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` 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);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.7.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// 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;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// 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;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @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_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @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 _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @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 _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @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 || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @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 || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `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);
_holderTokens[to].add(tokenId);
_tokenOwners.set(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); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(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"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @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()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @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 { }
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.7.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 () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.7.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File contracts/interfaces/ILottery.sol
pragma solidity ^0.7.6;
interface ILottery {
function registerToken(uint256 tokenId) external;
}
// File contracts/lottery/AladdinHonor.sol
pragma solidity ^0.7.6;
contract AladdinHonor is ERC721, Ownable, ReentrancyGuard {
event SetPendingMint(address indexed account, uint256 level);
event SetLevelURI(uint256 level, string url);
event SetLottery(address lottery);
struct PendingMint {
// current minted level.
uint128 mintedLevel;
// pending mint max level.
uint128 maxLevel;
}
/// The address of lottery contract.
address public lottery;
/// total token minted.
uint256 public tokenCounter;
/// mapping from user address to mint info.
mapping(address => PendingMint) public addressToPendingMint;
/// mapping from tokenId to level.
mapping(uint256 => uint256) public tokenToLevel;
/// mapping from level to token URI.
mapping(uint256 => string) public levelToURI;
constructor() ERC721("AladdinHonor", "ALDHONOR") Ownable() {}
/********************************** View Functions **********************************/
/// @notice Returns the token URI
/// @param tokenId The tokenId, from 1 to tokenCounter (max MAX_SUPPLY)
/// @dev Token owners can specify which tokenURI address to use
/// on a per-token basis using setTokenURIAddress
/// @return result A base64 encoded JSON string
function tokenURI(uint256 tokenId) public view override returns (string memory result) {
uint256 level = tokenToLevel[tokenId];
result = levelToURI[level];
}
/********************************** Mutated Functions **********************************/
function mint() external nonReentrant {
PendingMint memory pending = addressToPendingMint[msg.sender];
address _lottery = lottery;
uint256 _tokenCounter = tokenCounter;
for (uint256 level = pending.mintedLevel + 1; level <= pending.maxLevel; level++) {
tokenToLevel[_tokenCounter] = level;
_safeMint(msg.sender, _tokenCounter);
if (_lottery != address(0)) {
ILottery(_lottery).registerToken(_tokenCounter);
}
_tokenCounter += 1;
}
tokenCounter = _tokenCounter;
pending.mintedLevel = pending.maxLevel;
addressToPendingMint[msg.sender] = pending;
}
/********************************** Restricted Functions **********************************/
function setLevelURI(uint256 level, string memory uri) external onlyOwner {
require(1 <= level && level <= 9, "AladdinHonor: invalid level");
levelToURI[level] = uri;
emit SetLevelURI(level, uri);
}
function setLottery(address _lottery) external onlyOwner {
lottery = _lottery;
emit SetLottery(_lottery);
}
function setPendingMints(address[] memory users, uint256[] memory levels) external onlyOwner {
require(users.length == levels.length, "AladdinHonor: length mismatch");
for (uint256 i = 0; i < users.length; i++) {
_setPendingMint(users[i], levels[i]);
}
}
function setPendingMint(address user, uint256 level) external onlyOwner {
_setPendingMint(user, level);
}
/********************************** Internal Functions **********************************/
function _setPendingMint(address user, uint256 level) internal {
require(1 <= level && level <= 9, "AladdinHonor: invalid level");
PendingMint memory pending = addressToPendingMint[user];
require(pending.maxLevel < level, "AladdinHonor: level already set");
pending.maxLevel = uint128(level);
addressToPendingMint[user] = pending;
emit SetPendingMint(user, level);
}
} | mapping from level to token URI. | mapping(uint256 => string) public levelToURI;
| 10,727,732 | [
1,
6770,
628,
1801,
358,
1147,
3699,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
11890,
5034,
516,
533,
13,
1071,
1801,
774,
3098,
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
]
|
./full_match/137/0x4E42b784BB7bbc1106dCeb1776aBe4FB43E8041f/sources/project_/contracts/Marketplace.sol | ** vars */** structs */ | contract Marketplace is Initializable, Pausable, AccessControlUpgradeable {
bytes32 public constant AUCTION_FINISHER_ROLE = keccak256("AUCTION_FINISHER_ROLE");
uint32 public foundationFee;
uint32 public adminFee;
uint32 public adminFeeOnResell;
uint32 public creatorFee;
pragma solidity ^0.8.13;
struct Sale {
uint32 quantity;
uint256 price;
address seller;
bool resell;
}
struct AuctionState {
bool active;
uint256 creationTime;
uint256 price;
address seller;
bool resell;
}
mapping(uint256 => mapping(address => uint256)) public _auctionBids;
mapping(uint256 => mapping(address => Sale)) _sailingBox;
mapping(uint256 => AuctionState) _auctionState;
address foundationAddress;
address adminAddress;
AisNft aisNft;
event NftItemSold(uint256 tokenId, uint256 price, uint32 qty, address seller, address buyer, bool wasAuction);
event SaleCreated(uint256 tokenId, address creator, uint32 qty, uint256 price, bool isResell);
event SaleDropped(uint256 tokenId, address creator);
event AuctionCreated(uint256 tokenId, address creator, uint256 minPrice, uint256 buyNowPrice, bool isResell);
event BidCreated(uint256 tokenId, address bidder, uint256 addBid, uint256 totalBid);
event BidWithdrawn(uint256 tokenId, address bidder);
event AuctionClosed(uint256 tokenId, address seller);
event FundAdded(address user, uint256 amount);
event FundDropped(address user, uint256 amount);
mapping(address => uint256) public _fundRecord;
function initialize(address _nft) public initializer {
aisNft = AisNft(_nft);
foundationAddress = 0x36cDFAEE214a22584A900129dd3b2704Ec3cAB7a;
adminAddress = 0x8A58f8Ab955313DE64633F7Dc61F2dB1F12b9952;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(AUCTION_FINISHER_ROLE, _msgSender());
__Ownable_init();
}
function changeFoundationAddress(address _newAddress) public onlyOwner returns (bool) {
foundationAddress = _newAddress;
return true;
}
function changeAdminAddress(address _newAddress) public onlyOwner returns (bool) {
adminAddress = _newAddress;
return true;
}
modifier onlyTokenOwner(uint256 _tokenId, uint256 _quantity) {
require(aisNft.balanceOf(msg.sender, _tokenId) >= _quantity, "Not owner");
_;
}
modifier onlySeller(uint256 _tokenId) {
require(_sailingBox[_tokenId][msg.sender].seller == msg.sender, "Not a seller");
_;
}
modifier onlyActiveAuction(uint256 _tokenId) {
require(_auctionState[_tokenId].active, "This Auction is unavailable!");
_;
}
modifier isFeePercentagesLessThanMaximum(uint32[] memory _feePercentages) {
uint32 totalPercent;
for (uint256 i = 0; i < _feePercentages.length; i++) {
totalPercent = totalPercent + _feePercentages[i];
}
require(totalPercent <= 10000, "Fee percentages exceed maximum");
_;
}
modifier correctFeeRecipientsAndPercentages(
uint256 _recipientsLength,
uint256 _percentagesLength
modifier isFeePercentagesLessThanMaximum(uint32[] memory _feePercentages) {
uint32 totalPercent;
for (uint256 i = 0; i < _feePercentages.length; i++) {
totalPercent = totalPercent + _feePercentages[i];
}
require(totalPercent <= 10000, "Fee percentages exceed maximum");
_;
}
modifier correctFeeRecipientsAndPercentages(
uint256 _recipientsLength,
uint256 _percentagesLength
) {
require(
_recipientsLength == _percentagesLength,
"Recipients != percentages"
);
_;
}
modifier priceGreaterThanZero(uint256 _price) {
require(_price > 0, "Price cannot be 0");
_;
}
function contractBalance() public view returns (uint256) {
return address(this).balance;
}
function getSailingList(uint256 _tokenId) public view returns (Sale memory) {
return _sailingBox[_tokenId][msg.sender];
}
function getSailingParams(uint256 _tokenId, address _seller) public view returns (uint256, uint32){
return (_sailingBox[_tokenId][_seller].price, _sailingBox[_tokenId][_seller].quantity);
}
function getStateAuction(uint256 _tokenId) public view returns (AuctionState memory){
return _auctionState[_tokenId];
}
function getAuctionBid(uint256 _tokenId, address bidder) public view returns (uint256){
return _auctionBids[_tokenId][bidder];
}
function getUserFund(address user) public view returns (uint256) {
return _fundRecord[user];
}
function createSailing(
string memory _uri,
uint256 _price,
uint32 _quantity,
uint32 _galleryFee,
address _galleryAddress,
address[] memory _collaborators,
uint32[] memory _collaboratorsFee)
priceGreaterThanZero(_price)
external returns (bool, uint256)
{
uint256 tokenId = aisNft.createNftItem(msg.sender, _uri, _quantity, _galleryFee, _galleryAddress, _collaborators, _collaboratorsFee);
_setupSale(tokenId, _quantity, _price, false);
return (true, tokenId);
}
function resell(uint256 _tokenId, uint32 _quantity, uint256 _price)
priceGreaterThanZero(_price) onlyTokenOwner(_tokenId, _quantity)
external returns (bool)
{
require(!_auctionState[_tokenId].active, "resale is forbidden on active auction");
require(!aisNft.getNftItem(_tokenId).isMembership, "Membership token can't be sold");
_setupSale(_tokenId, _quantity, _price, true);
return true;
}
function dropSailingList(uint256 _tokenId) external onlySeller(_tokenId) returns (bool) {
delete _sailingBox[_tokenId][msg.sender];
emit SaleDropped(_tokenId, msg.sender);
return true;
}
function createAuction(string memory _uri,
uint256 _minPrice,
uint256 _buyNowPrice,
uint32 _galleryFee,
address _galleryAddress,
address[] memory _collaborators,
uint32[] memory _collaboratorsFee)
priceGreaterThanZero(_minPrice)
external returns (uint256)
{
uint256 tokenId = aisNft.createNftItem(msg.sender, _uri, 1, _galleryFee, _galleryAddress, _collaborators, _collaboratorsFee);
_setupAuction(tokenId, _minPrice, _buyNowPrice, false);
return tokenId;
}
function resaleWithAuction(uint256 _tokenId, uint256 _minPrice, uint256 _buyNowPrice)
priceGreaterThanZero(_minPrice) onlyTokenOwner(_tokenId, 1)
external returns (bool){
require(!_auctionState[_tokenId].active, "resale is forbidden on active auction");
require(aisNft.getNftItem(_tokenId).quantity == 1, "Only NFT with 1 of a kind can create auction");
require(!aisNft.getNftItem(_tokenId).isMembership, "Membership token can't be sold");
_setupAuction(_tokenId, _minPrice, _buyNowPrice, true);
return true;
}
function multiBuy(uint256[] memory _tokenIds, uint32[] memory _quantities, address[] memory _sellers) external payable returns (bool)
{
uint256 leftValue = msg.value;
for (uint256 i = 0; i < _tokenIds.length; ++i) {
leftValue -= _buy(_tokenIds[i], _quantities[i], _sellers[i], leftValue);
}
if (leftValue > 0) {
_addFunds(msg.sender, leftValue);
}
return true;
}
function multiBuy(uint256[] memory _tokenIds, uint32[] memory _quantities, address[] memory _sellers) external payable returns (bool)
{
uint256 leftValue = msg.value;
for (uint256 i = 0; i < _tokenIds.length; ++i) {
leftValue -= _buy(_tokenIds[i], _quantities[i], _sellers[i], leftValue);
}
if (leftValue > 0) {
_addFunds(msg.sender, leftValue);
}
return true;
}
function multiBuy(uint256[] memory _tokenIds, uint32[] memory _quantities, address[] memory _sellers) external payable returns (bool)
{
uint256 leftValue = msg.value;
for (uint256 i = 0; i < _tokenIds.length; ++i) {
leftValue -= _buy(_tokenIds[i], _quantities[i], _sellers[i], leftValue);
}
if (leftValue > 0) {
_addFunds(msg.sender, leftValue);
}
return true;
}
function buy(uint256 _tokenId, uint32 _quantity, address _seller) external payable returns (bool)
{
uint256 leftValue = msg.value;
leftValue -= _buy(_tokenId, _quantity, _seller, leftValue);
if (leftValue > 0) {
_addFunds(msg.sender, leftValue);
}
return true;
}
function buy(uint256 _tokenId, uint32 _quantity, address _seller) external payable returns (bool)
{
uint256 leftValue = msg.value;
leftValue -= _buy(_tokenId, _quantity, _seller, leftValue);
if (leftValue > 0) {
_addFunds(msg.sender, leftValue);
}
return true;
}
function bidAuction(uint256 _tokenId, uint256 addBid) external onlyActiveAuction(_tokenId) returns (bool){
AuctionState memory auction = _auctionState[_tokenId];
require(_auctionBids[_tokenId][msg.sender] + addBid >= auction.price, "Price must be bigger to listing price");
require(aisNft.balanceOf(auction.seller, _tokenId) >= 1, "Seller address does not hold token");
require(_fundRecord[msg.sender] >= addBid, "Not enough funds for bidding");
uint256 buyNowPrice = _sailingBox[_tokenId][auction.seller].price;
if (buyNowPrice > 0) {
require(buyNowPrice < _fundRecord[msg.sender] + addBid, "Bidding amount must be less then buyNow");
}
_fundRecord[msg.sender] -= addBid;
_auctionBids[_tokenId][msg.sender] += addBid;
emit BidCreated(_tokenId, msg.sender, addBid, _auctionBids[_tokenId][msg.sender]);
return true;
}
function bidAuction(uint256 _tokenId, uint256 addBid) external onlyActiveAuction(_tokenId) returns (bool){
AuctionState memory auction = _auctionState[_tokenId];
require(_auctionBids[_tokenId][msg.sender] + addBid >= auction.price, "Price must be bigger to listing price");
require(aisNft.balanceOf(auction.seller, _tokenId) >= 1, "Seller address does not hold token");
require(_fundRecord[msg.sender] >= addBid, "Not enough funds for bidding");
uint256 buyNowPrice = _sailingBox[_tokenId][auction.seller].price;
if (buyNowPrice > 0) {
require(buyNowPrice < _fundRecord[msg.sender] + addBid, "Bidding amount must be less then buyNow");
}
_fundRecord[msg.sender] -= addBid;
_auctionBids[_tokenId][msg.sender] += addBid;
emit BidCreated(_tokenId, msg.sender, addBid, _auctionBids[_tokenId][msg.sender]);
return true;
}
function withdrawBid(uint256 _tokenId) external returns (bool) {
require(_auctionBids[_tokenId][msg.sender] > 0, "No bids found");
uint256 _bidAmount = _auctionBids[_tokenId][msg.sender];
delete _auctionBids[_tokenId][msg.sender];
emit BidWithdrawn(_tokenId, msg.sender);
return _payout(msg.sender, _bidAmount, true);
}
function transferBidToBalance(uint256 _tokenId) external returns (bool) {
require(_auctionBids[_tokenId][msg.sender] > 0, "No bids found");
uint256 _bidAmount = _auctionBids[_tokenId][msg.sender];
delete _auctionBids[_tokenId][msg.sender];
emit BidWithdrawn(_tokenId, msg.sender);
_addFunds(msg.sender, _bidAmount);
return true;
}
function endAuction(uint256 _tokenId, address winner) external onlyTokenOwner(_tokenId, 1) onlyActiveAuction(_tokenId) returns (bool){
_endAuction(_tokenId, winner);
return true;
}
function endAuctionByAdmin(uint256 _tokenId, address winner) external onlyActiveAuction(_tokenId) returns (bool){
require(
hasRole(AUCTION_FINISHER_ROLE, _msgSender()),
"must have admin role to end auction"
);
_endAuction(_tokenId, winner);
return true;
}
function closeAuction(uint256 _tokenId) external onlyTokenOwner(_tokenId, 1) returns (bool){
delete _auctionState[_tokenId];
emit AuctionClosed(_tokenId, msg.sender);
return true;
}
function addFund(uint256 _amount) external payable returns (bool)
{
require(_amount > 0 && _amount == msg.value, "Please submit the valid amounts!");
_fundRecord[msg.sender] += _amount;
emit FundAdded(msg.sender, _amount);
return true;
}
function dropFund(uint256 _amount) external returns (bool)
{
require(_amount > 0 && _amount <= _fundRecord[msg.sender], "Please submit the valid amounts!");
_fundRecord[msg.sender] -= _amount;
_payout(msg.sender, _amount, false);
emit FundDropped(msg.sender, _amount);
return true;
}
function _setupSale(uint256 _tokenId, uint32 _quantity, uint256 _price, bool _resell) internal {
_sailingBox[_tokenId][msg.sender] = Sale(_quantity, _price, msg.sender, _resell);
emit SaleCreated(_tokenId, msg.sender, _quantity, _price, _resell);
}
function _setupAuction(uint256 _tokenId, uint256 _minPrice, uint256 _buyNowPrice, bool _resell) internal {
require(_buyNowPrice == 0 || _buyNowPrice > _minPrice, "buyNowPrice must be more then price");
if (_buyNowPrice > 0) {
_sailingBox[_tokenId][msg.sender] = Sale(1, _minPrice, msg.sender, _resell);
}
_auctionState[_tokenId] = AuctionState(true, block.timestamp, 0, _minPrice, 0, msg.sender, _resell);
emit AuctionCreated(_tokenId, msg.sender, _minPrice, _buyNowPrice, _resell);
}
function _setupAuction(uint256 _tokenId, uint256 _minPrice, uint256 _buyNowPrice, bool _resell) internal {
require(_buyNowPrice == 0 || _buyNowPrice > _minPrice, "buyNowPrice must be more then price");
if (_buyNowPrice > 0) {
_sailingBox[_tokenId][msg.sender] = Sale(1, _minPrice, msg.sender, _resell);
}
_auctionState[_tokenId] = AuctionState(true, block.timestamp, 0, _minPrice, 0, msg.sender, _resell);
emit AuctionCreated(_tokenId, msg.sender, _minPrice, _buyNowPrice, _resell);
}
function _buy(uint256 _tokenId, uint32 _quantity, address _seller, uint256 _totalAmountLeft) internal returns (uint256) {
uint32 quantity = _sailingBox[_tokenId][_seller].quantity;
uint256 price = _sailingBox[_tokenId][_seller].price;
address seller = _sailingBox[_tokenId][_seller].seller;
bool isResell = _sailingBox[_tokenId][_seller].resell;
require(aisNft.balanceOf(seller, _tokenId) >= _quantity, "Seller address does not hold token(s)");
uint256 total = price * _quantity;
require(_totalAmountLeft >= total, "Price must be bigger to listing price");
require(_quantity <= quantity, "Quantity can't be more then listing");
_sailingBox[_tokenId][_seller].quantity -= _quantity;
if (_auctionState[_tokenId].active) {
delete _auctionState[_tokenId];
}
aisNft.marketplaceTransfer(_seller, msg.sender, _tokenId, _quantity);
_separateFees(_tokenId, seller, total, isResell);
emit NftItemSold(_tokenId, price, _quantity, _seller, msg.sender, false);
return total;
}
function _buy(uint256 _tokenId, uint32 _quantity, address _seller, uint256 _totalAmountLeft) internal returns (uint256) {
uint32 quantity = _sailingBox[_tokenId][_seller].quantity;
uint256 price = _sailingBox[_tokenId][_seller].price;
address seller = _sailingBox[_tokenId][_seller].seller;
bool isResell = _sailingBox[_tokenId][_seller].resell;
require(aisNft.balanceOf(seller, _tokenId) >= _quantity, "Seller address does not hold token(s)");
uint256 total = price * _quantity;
require(_totalAmountLeft >= total, "Price must be bigger to listing price");
require(_quantity <= quantity, "Quantity can't be more then listing");
_sailingBox[_tokenId][_seller].quantity -= _quantity;
if (_auctionState[_tokenId].active) {
delete _auctionState[_tokenId];
}
aisNft.marketplaceTransfer(_seller, msg.sender, _tokenId, _quantity);
_separateFees(_tokenId, seller, total, isResell);
emit NftItemSold(_tokenId, price, _quantity, _seller, msg.sender, false);
return total;
}
function _endAuction(uint256 _tokenId, address _winner) internal {
uint256 bidAmount = _auctionBids[_tokenId][_winner];
bool isResell = _auctionState[_tokenId].resell;
require(bidAmount >= _auctionState[_tokenId].price, "Bid is not valid for this user");
address seller = _auctionState[_tokenId].seller;
_sailingBox[_tokenId][seller].seller = address(0);
_sailingBox[_tokenId][seller].price = 0;
_sailingBox[_tokenId][seller].quantity = 0;
delete _auctionBids[_tokenId][_winner];
delete _auctionState[_tokenId];
aisNft.marketplaceTransfer(seller, _winner, _tokenId, 1);
_separateFees(_tokenId, seller, bidAmount, isResell);
emit NftItemSold(_tokenId, bidAmount, 1, seller, _winner, true);
}
function _separateFees(uint256 _tokenId, address _seller, uint256 _price, bool _resell) internal returns (bool)
{
AisNft.NftItem memory nft = aisNft.getNftItem(_tokenId);
address creator = nft.creator;
uint256 foundationPart;
uint256 adminPart;
uint256 galleryPart;
uint256 creatorPart;
uint256 resellerPart;
if (creator == adminAddress && !_resell) {
foundationPart = _price * foundationFee / 10000;
creatorPart = _price - foundationPart;
if (!_resell) {
foundationPart = _price * foundationFee / 10000;
adminPart = _price * adminFee / 10000;
if (nft.isGallery) {
uint256 galleryFee = nft.galleryFee;
galleryPart = (_price - foundationPart - adminPart) * galleryFee / 10000;
}
creatorPart = _price - foundationPart - adminPart - galleryPart;
adminPart = _price * adminFeeOnResell / 10000;
creatorPart = _price * creatorFee / 10000;
resellerPart = _price - adminPart - creatorPart;
}
}
if (foundationPart > 0) {
_fundRecord[foundationAddress] += foundationPart;
}
if (adminPart > 0) {
_fundRecord[adminAddress] += adminPart;
}
if (galleryPart > 0) {
_fundRecord[nft.galleryAddress] += galleryPart;
}
if (resellerPart > 0) {
_fundRecord[_seller] += resellerPart;
}
if (creatorPart > 0) {
uint256 feesPaid = 0;
for (uint256 i = 0; i < nft.collaborators.length; i++) {
uint256 fee = creatorPart * nft.collaboratorsFee[i] / 10000;
feesPaid += fee;
_fundRecord[nft.collaborators[i]] += fee;
}
_fundRecord[creator] += (creatorPart - feesPaid);
}
return true;
}
function _separateFees(uint256 _tokenId, address _seller, uint256 _price, bool _resell) internal returns (bool)
{
AisNft.NftItem memory nft = aisNft.getNftItem(_tokenId);
address creator = nft.creator;
uint256 foundationPart;
uint256 adminPart;
uint256 galleryPart;
uint256 creatorPart;
uint256 resellerPart;
if (creator == adminAddress && !_resell) {
foundationPart = _price * foundationFee / 10000;
creatorPart = _price - foundationPart;
if (!_resell) {
foundationPart = _price * foundationFee / 10000;
adminPart = _price * adminFee / 10000;
if (nft.isGallery) {
uint256 galleryFee = nft.galleryFee;
galleryPart = (_price - foundationPart - adminPart) * galleryFee / 10000;
}
creatorPart = _price - foundationPart - adminPart - galleryPart;
adminPart = _price * adminFeeOnResell / 10000;
creatorPart = _price * creatorFee / 10000;
resellerPart = _price - adminPart - creatorPart;
}
}
if (foundationPart > 0) {
_fundRecord[foundationAddress] += foundationPart;
}
if (adminPart > 0) {
_fundRecord[adminAddress] += adminPart;
}
if (galleryPart > 0) {
_fundRecord[nft.galleryAddress] += galleryPart;
}
if (resellerPart > 0) {
_fundRecord[_seller] += resellerPart;
}
if (creatorPart > 0) {
uint256 feesPaid = 0;
for (uint256 i = 0; i < nft.collaborators.length; i++) {
uint256 fee = creatorPart * nft.collaboratorsFee[i] / 10000;
feesPaid += fee;
_fundRecord[nft.collaborators[i]] += fee;
}
_fundRecord[creator] += (creatorPart - feesPaid);
}
return true;
}
} else {
function _separateFees(uint256 _tokenId, address _seller, uint256 _price, bool _resell) internal returns (bool)
{
AisNft.NftItem memory nft = aisNft.getNftItem(_tokenId);
address creator = nft.creator;
uint256 foundationPart;
uint256 adminPart;
uint256 galleryPart;
uint256 creatorPart;
uint256 resellerPart;
if (creator == adminAddress && !_resell) {
foundationPart = _price * foundationFee / 10000;
creatorPart = _price - foundationPart;
if (!_resell) {
foundationPart = _price * foundationFee / 10000;
adminPart = _price * adminFee / 10000;
if (nft.isGallery) {
uint256 galleryFee = nft.galleryFee;
galleryPart = (_price - foundationPart - adminPart) * galleryFee / 10000;
}
creatorPart = _price - foundationPart - adminPart - galleryPart;
adminPart = _price * adminFeeOnResell / 10000;
creatorPart = _price * creatorFee / 10000;
resellerPart = _price - adminPart - creatorPart;
}
}
if (foundationPart > 0) {
_fundRecord[foundationAddress] += foundationPart;
}
if (adminPart > 0) {
_fundRecord[adminAddress] += adminPart;
}
if (galleryPart > 0) {
_fundRecord[nft.galleryAddress] += galleryPart;
}
if (resellerPart > 0) {
_fundRecord[_seller] += resellerPart;
}
if (creatorPart > 0) {
uint256 feesPaid = 0;
for (uint256 i = 0; i < nft.collaborators.length; i++) {
uint256 fee = creatorPart * nft.collaboratorsFee[i] / 10000;
feesPaid += fee;
_fundRecord[nft.collaborators[i]] += fee;
}
_fundRecord[creator] += (creatorPart - feesPaid);
}
return true;
}
function _separateFees(uint256 _tokenId, address _seller, uint256 _price, bool _resell) internal returns (bool)
{
AisNft.NftItem memory nft = aisNft.getNftItem(_tokenId);
address creator = nft.creator;
uint256 foundationPart;
uint256 adminPart;
uint256 galleryPart;
uint256 creatorPart;
uint256 resellerPart;
if (creator == adminAddress && !_resell) {
foundationPart = _price * foundationFee / 10000;
creatorPart = _price - foundationPart;
if (!_resell) {
foundationPart = _price * foundationFee / 10000;
adminPart = _price * adminFee / 10000;
if (nft.isGallery) {
uint256 galleryFee = nft.galleryFee;
galleryPart = (_price - foundationPart - adminPart) * galleryFee / 10000;
}
creatorPart = _price - foundationPart - adminPart - galleryPart;
adminPart = _price * adminFeeOnResell / 10000;
creatorPart = _price * creatorFee / 10000;
resellerPart = _price - adminPart - creatorPart;
}
}
if (foundationPart > 0) {
_fundRecord[foundationAddress] += foundationPart;
}
if (adminPart > 0) {
_fundRecord[adminAddress] += adminPart;
}
if (galleryPart > 0) {
_fundRecord[nft.galleryAddress] += galleryPart;
}
if (resellerPart > 0) {
_fundRecord[_seller] += resellerPart;
}
if (creatorPart > 0) {
uint256 feesPaid = 0;
for (uint256 i = 0; i < nft.collaborators.length; i++) {
uint256 fee = creatorPart * nft.collaboratorsFee[i] / 10000;
feesPaid += fee;
_fundRecord[nft.collaborators[i]] += fee;
}
_fundRecord[creator] += (creatorPart - feesPaid);
}
return true;
}
} else {
function _separateFees(uint256 _tokenId, address _seller, uint256 _price, bool _resell) internal returns (bool)
{
AisNft.NftItem memory nft = aisNft.getNftItem(_tokenId);
address creator = nft.creator;
uint256 foundationPart;
uint256 adminPart;
uint256 galleryPart;
uint256 creatorPart;
uint256 resellerPart;
if (creator == adminAddress && !_resell) {
foundationPart = _price * foundationFee / 10000;
creatorPart = _price - foundationPart;
if (!_resell) {
foundationPart = _price * foundationFee / 10000;
adminPart = _price * adminFee / 10000;
if (nft.isGallery) {
uint256 galleryFee = nft.galleryFee;
galleryPart = (_price - foundationPart - adminPart) * galleryFee / 10000;
}
creatorPart = _price - foundationPart - adminPart - galleryPart;
adminPart = _price * adminFeeOnResell / 10000;
creatorPart = _price * creatorFee / 10000;
resellerPart = _price - adminPart - creatorPart;
}
}
if (foundationPart > 0) {
_fundRecord[foundationAddress] += foundationPart;
}
if (adminPart > 0) {
_fundRecord[adminAddress] += adminPart;
}
if (galleryPart > 0) {
_fundRecord[nft.galleryAddress] += galleryPart;
}
if (resellerPart > 0) {
_fundRecord[_seller] += resellerPart;
}
if (creatorPart > 0) {
uint256 feesPaid = 0;
for (uint256 i = 0; i < nft.collaborators.length; i++) {
uint256 fee = creatorPart * nft.collaboratorsFee[i] / 10000;
feesPaid += fee;
_fundRecord[nft.collaborators[i]] += fee;
}
_fundRecord[creator] += (creatorPart - feesPaid);
}
return true;
}
function _separateFees(uint256 _tokenId, address _seller, uint256 _price, bool _resell) internal returns (bool)
{
AisNft.NftItem memory nft = aisNft.getNftItem(_tokenId);
address creator = nft.creator;
uint256 foundationPart;
uint256 adminPart;
uint256 galleryPart;
uint256 creatorPart;
uint256 resellerPart;
if (creator == adminAddress && !_resell) {
foundationPart = _price * foundationFee / 10000;
creatorPart = _price - foundationPart;
if (!_resell) {
foundationPart = _price * foundationFee / 10000;
adminPart = _price * adminFee / 10000;
if (nft.isGallery) {
uint256 galleryFee = nft.galleryFee;
galleryPart = (_price - foundationPart - adminPart) * galleryFee / 10000;
}
creatorPart = _price - foundationPart - adminPart - galleryPart;
adminPart = _price * adminFeeOnResell / 10000;
creatorPart = _price * creatorFee / 10000;
resellerPart = _price - adminPart - creatorPart;
}
}
if (foundationPart > 0) {
_fundRecord[foundationAddress] += foundationPart;
}
if (adminPart > 0) {
_fundRecord[adminAddress] += adminPart;
}
if (galleryPart > 0) {
_fundRecord[nft.galleryAddress] += galleryPart;
}
if (resellerPart > 0) {
_fundRecord[_seller] += resellerPart;
}
if (creatorPart > 0) {
uint256 feesPaid = 0;
for (uint256 i = 0; i < nft.collaborators.length; i++) {
uint256 fee = creatorPart * nft.collaboratorsFee[i] / 10000;
feesPaid += fee;
_fundRecord[nft.collaborators[i]] += fee;
}
_fundRecord[creator] += (creatorPart - feesPaid);
}
return true;
}
function _separateFees(uint256 _tokenId, address _seller, uint256 _price, bool _resell) internal returns (bool)
{
AisNft.NftItem memory nft = aisNft.getNftItem(_tokenId);
address creator = nft.creator;
uint256 foundationPart;
uint256 adminPart;
uint256 galleryPart;
uint256 creatorPart;
uint256 resellerPart;
if (creator == adminAddress && !_resell) {
foundationPart = _price * foundationFee / 10000;
creatorPart = _price - foundationPart;
if (!_resell) {
foundationPart = _price * foundationFee / 10000;
adminPart = _price * adminFee / 10000;
if (nft.isGallery) {
uint256 galleryFee = nft.galleryFee;
galleryPart = (_price - foundationPart - adminPart) * galleryFee / 10000;
}
creatorPart = _price - foundationPart - adminPart - galleryPart;
adminPart = _price * adminFeeOnResell / 10000;
creatorPart = _price * creatorFee / 10000;
resellerPart = _price - adminPart - creatorPart;
}
}
if (foundationPart > 0) {
_fundRecord[foundationAddress] += foundationPart;
}
if (adminPart > 0) {
_fundRecord[adminAddress] += adminPart;
}
if (galleryPart > 0) {
_fundRecord[nft.galleryAddress] += galleryPart;
}
if (resellerPart > 0) {
_fundRecord[_seller] += resellerPart;
}
if (creatorPart > 0) {
uint256 feesPaid = 0;
for (uint256 i = 0; i < nft.collaborators.length; i++) {
uint256 fee = creatorPart * nft.collaboratorsFee[i] / 10000;
feesPaid += fee;
_fundRecord[nft.collaborators[i]] += fee;
}
_fundRecord[creator] += (creatorPart - feesPaid);
}
return true;
}
function _separateFees(uint256 _tokenId, address _seller, uint256 _price, bool _resell) internal returns (bool)
{
AisNft.NftItem memory nft = aisNft.getNftItem(_tokenId);
address creator = nft.creator;
uint256 foundationPart;
uint256 adminPart;
uint256 galleryPart;
uint256 creatorPart;
uint256 resellerPart;
if (creator == adminAddress && !_resell) {
foundationPart = _price * foundationFee / 10000;
creatorPart = _price - foundationPart;
if (!_resell) {
foundationPart = _price * foundationFee / 10000;
adminPart = _price * adminFee / 10000;
if (nft.isGallery) {
uint256 galleryFee = nft.galleryFee;
galleryPart = (_price - foundationPart - adminPart) * galleryFee / 10000;
}
creatorPart = _price - foundationPart - adminPart - galleryPart;
adminPart = _price * adminFeeOnResell / 10000;
creatorPart = _price * creatorFee / 10000;
resellerPart = _price - adminPart - creatorPart;
}
}
if (foundationPart > 0) {
_fundRecord[foundationAddress] += foundationPart;
}
if (adminPart > 0) {
_fundRecord[adminAddress] += adminPart;
}
if (galleryPart > 0) {
_fundRecord[nft.galleryAddress] += galleryPart;
}
if (resellerPart > 0) {
_fundRecord[_seller] += resellerPart;
}
if (creatorPart > 0) {
uint256 feesPaid = 0;
for (uint256 i = 0; i < nft.collaborators.length; i++) {
uint256 fee = creatorPart * nft.collaboratorsFee[i] / 10000;
feesPaid += fee;
_fundRecord[nft.collaborators[i]] += fee;
}
_fundRecord[creator] += (creatorPart - feesPaid);
}
return true;
}
function _separateFees(uint256 _tokenId, address _seller, uint256 _price, bool _resell) internal returns (bool)
{
AisNft.NftItem memory nft = aisNft.getNftItem(_tokenId);
address creator = nft.creator;
uint256 foundationPart;
uint256 adminPart;
uint256 galleryPart;
uint256 creatorPart;
uint256 resellerPart;
if (creator == adminAddress && !_resell) {
foundationPart = _price * foundationFee / 10000;
creatorPart = _price - foundationPart;
if (!_resell) {
foundationPart = _price * foundationFee / 10000;
adminPart = _price * adminFee / 10000;
if (nft.isGallery) {
uint256 galleryFee = nft.galleryFee;
galleryPart = (_price - foundationPart - adminPart) * galleryFee / 10000;
}
creatorPart = _price - foundationPart - adminPart - galleryPart;
adminPart = _price * adminFeeOnResell / 10000;
creatorPart = _price * creatorFee / 10000;
resellerPart = _price - adminPart - creatorPart;
}
}
if (foundationPart > 0) {
_fundRecord[foundationAddress] += foundationPart;
}
if (adminPart > 0) {
_fundRecord[adminAddress] += adminPart;
}
if (galleryPart > 0) {
_fundRecord[nft.galleryAddress] += galleryPart;
}
if (resellerPart > 0) {
_fundRecord[_seller] += resellerPart;
}
if (creatorPart > 0) {
uint256 feesPaid = 0;
for (uint256 i = 0; i < nft.collaborators.length; i++) {
uint256 fee = creatorPart * nft.collaboratorsFee[i] / 10000;
feesPaid += fee;
_fundRecord[nft.collaborators[i]] += fee;
}
_fundRecord[creator] += (creatorPart - feesPaid);
}
return true;
}
function _separateFees(uint256 _tokenId, address _seller, uint256 _price, bool _resell) internal returns (bool)
{
AisNft.NftItem memory nft = aisNft.getNftItem(_tokenId);
address creator = nft.creator;
uint256 foundationPart;
uint256 adminPart;
uint256 galleryPart;
uint256 creatorPart;
uint256 resellerPart;
if (creator == adminAddress && !_resell) {
foundationPart = _price * foundationFee / 10000;
creatorPart = _price - foundationPart;
if (!_resell) {
foundationPart = _price * foundationFee / 10000;
adminPart = _price * adminFee / 10000;
if (nft.isGallery) {
uint256 galleryFee = nft.galleryFee;
galleryPart = (_price - foundationPart - adminPart) * galleryFee / 10000;
}
creatorPart = _price - foundationPart - adminPart - galleryPart;
adminPart = _price * adminFeeOnResell / 10000;
creatorPart = _price * creatorFee / 10000;
resellerPart = _price - adminPart - creatorPart;
}
}
if (foundationPart > 0) {
_fundRecord[foundationAddress] += foundationPart;
}
if (adminPart > 0) {
_fundRecord[adminAddress] += adminPart;
}
if (galleryPart > 0) {
_fundRecord[nft.galleryAddress] += galleryPart;
}
if (resellerPart > 0) {
_fundRecord[_seller] += resellerPart;
}
if (creatorPart > 0) {
uint256 feesPaid = 0;
for (uint256 i = 0; i < nft.collaborators.length; i++) {
uint256 fee = creatorPart * nft.collaboratorsFee[i] / 10000;
feesPaid += fee;
_fundRecord[nft.collaborators[i]] += fee;
}
_fundRecord[creator] += (creatorPart - feesPaid);
}
return true;
}
function _addFunds(address _user, uint256 _amount) internal returns (bool)
{
_fundRecord[_user] += _amount;
emit FundAdded(_user, _amount);
return true;
}
function _payout(address _recipient, uint256 _amount, bool addInFundsOnFail) internal returns (bool) {
if (!success) {
if (addInFundsOnFail) {
_addFunds(_recipient, _amount);
require(success, "payout failed");
}
}
return success;
}
(bool success,) = payable(_recipient).call{value : _amount, gas : 20000}("");
function _payout(address _recipient, uint256 _amount, bool addInFundsOnFail) internal returns (bool) {
if (!success) {
if (addInFundsOnFail) {
_addFunds(_recipient, _amount);
require(success, "payout failed");
}
}
return success;
}
function _payout(address _recipient, uint256 _amount, bool addInFundsOnFail) internal returns (bool) {
if (!success) {
if (addInFundsOnFail) {
_addFunds(_recipient, _amount);
require(success, "payout failed");
}
}
return success;
}
} else {
}
| 3,769,286 | [
1,
4699,
342,
8179,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
6622,
24577,
353,
10188,
6934,
16,
21800,
16665,
16,
24349,
10784,
429,
288,
203,
203,
565,
1731,
1578,
1071,
5381,
432,
27035,
67,
23259,
654,
67,
16256,
273,
417,
24410,
581,
5034,
2932,
14237,
3106,
67,
23259,
654,
67,
16256,
8863,
203,
203,
565,
2254,
1578,
1071,
1392,
367,
14667,
31,
203,
565,
2254,
1578,
1071,
3981,
14667,
31,
203,
203,
565,
2254,
1578,
1071,
3981,
14667,
1398,
607,
1165,
31,
203,
565,
2254,
1578,
1071,
11784,
14667,
31,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
3437,
31,
203,
565,
1958,
348,
5349,
288,
203,
3639,
2254,
1578,
10457,
31,
203,
3639,
2254,
5034,
6205,
31,
203,
3639,
1758,
29804,
31,
203,
3639,
1426,
400,
1165,
31,
203,
565,
289,
203,
203,
565,
1958,
432,
4062,
1119,
288,
203,
3639,
1426,
2695,
31,
203,
3639,
2254,
5034,
6710,
950,
31,
203,
3639,
2254,
5034,
6205,
31,
203,
3639,
1758,
29804,
31,
203,
3639,
1426,
400,
1165,
31,
203,
565,
289,
203,
203,
565,
2874,
12,
11890,
5034,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
1071,
389,
69,
4062,
38,
2232,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
2874,
12,
2867,
516,
348,
5349,
3719,
389,
87,
671,
13488,
31,
203,
565,
2874,
12,
11890,
5034,
516,
432,
4062,
1119,
13,
389,
69,
4062,
1119,
31,
203,
203,
565,
1758,
1392,
367,
1887,
31,
203,
203,
565,
1758,
3981,
1887,
31,
203,
203,
565,
432,
291,
50,
1222,
279,
291,
50,
1222,
31,
203,
203,
565,
2
]
|
pragma solidity ^0.6.0;
abstract contract Context {
function _MSGSENDER85() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA913() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED414(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER85();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED414(address(0), msgSender);
}
function OWNER64() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER222() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER85(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP892() public ONLYOWNER222 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED414(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP29(address newOwner) public ONLYOWNER222 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP883(newOwner);
}
function _TRANSFEROWNERSHIP883(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED414(_owner, newOwner);
_owner = newOwner;
}
}
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;
}
function _ADD747(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
if (!_CONTAINS554(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;
}
}
function _REMOVE891(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
// 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;
}
}
function _CONTAINS554(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING
return set._indexes[value] != 0;
}
function _LENGTH41(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING
return set._values.length;
}
function _AT103(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
function ADD466(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD747(set._inner, bytes32(uint256(value)));
}
function REMOVE507(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE891(set._inner, bytes32(uint256(value)));
}
function CONTAINS613(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS554(set._inner, bytes32(uint256(value)));
}
function LENGTH534(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH41(set._inner);
}
function AT564(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING
return address(uint256(_AT103(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
function ADD466(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD747(set._inner, bytes32(value));
}
function REMOVE507(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE891(set._inner, bytes32(value));
}
function CONTAINS613(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS554(set._inner, bytes32(value));
}
function LENGTH534(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH41(set._inner);
}
function AT564(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING
return uint256(_AT103(set._inner, index));
}
}
abstract contract AccessControl is Context {
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_role995 = 0x00; //inject NONSTANDARD NAMING
event ROLEADMINCHANGED684(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); //inject NONSTANDARD NAMING
event ROLEGRANTED165(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING
event ROLEREVOKED393(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING
function HASROLE479(bytes32 role, address account) public view returns (bool) { //inject NONSTANDARD NAMING
return _roles[role].members.CONTAINS613(account);
}
function GETROLEMEMBERCOUNT957(bytes32 role) public view returns (uint256) { //inject NONSTANDARD NAMING
return _roles[role].members.LENGTH534();
}
function GETROLEMEMBER575(bytes32 role, uint256 index) public view returns (address) { //inject NONSTANDARD NAMING
return _roles[role].members.AT564(index);
}
function GETROLEADMIN486(bytes32 role) public view returns (bytes32) { //inject NONSTANDARD NAMING
return _roles[role].adminRole;
}
function GRANTROLE655(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(HASROLE479(_roles[role].adminRole, _MSGSENDER85()), "AccessControl: sender must be an admin to grant");
_GRANTROLE46(role, account);
}
function REVOKEROLE852(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(HASROLE479(_roles[role].adminRole, _MSGSENDER85()), "AccessControl: sender must be an admin to revoke");
_REVOKEROLE383(role, account);
}
function RENOUNCEROLE241(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(account == _MSGSENDER85(), "AccessControl: can only renounce roles for self");
_REVOKEROLE383(role, account);
}
function _SETUPROLE796(bytes32 role, address account) internal virtual { //inject NONSTANDARD NAMING
_GRANTROLE46(role, account);
}
function _SETROLEADMIN129(bytes32 role, bytes32 adminRole) internal virtual { //inject NONSTANDARD NAMING
emit ROLEADMINCHANGED684(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _GRANTROLE46(bytes32 role, address account) private { //inject NONSTANDARD NAMING
if (_roles[role].members.ADD466(account)) {
emit ROLEGRANTED165(role, account, _MSGSENDER85());
}
}
function _REVOKEROLE383(bytes32 role, address account) private { //inject NONSTANDARD NAMING
if (_roles[role].members.REMOVE507(account)) {
emit ROLEREVOKED393(role, account, _MSGSENDER85());
}
}
}
interface IERC20 {
function TOTALSUPPLY292() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF687(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER708(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE385(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE878(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM598(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER38(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL749(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD466(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB765(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB765(a, b, "SafeMath: subtraction overflow");
}
function SUB765(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL597(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV787(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV787(a, b, "SafeMath: division by zero");
}
function DIV787(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD531(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD531(a, b, "SafeMath: modulo by zero");
}
function MOD531(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
contract ERC20 is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => bool) public power;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME385() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL654() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS455() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY292() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF687(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER708(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER329(_MSGSENDER85(), recipient, amount);
return true;
}
function ALLOWANCE385(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE878(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE176(_MSGSENDER85(), spender, amount);
return true;
}
function TRANSFERFROM598(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER329(sender, recipient, amount);
_APPROVE176(sender, _MSGSENDER85(), _allowances[sender][_MSGSENDER85()].SUB765(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE100(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE176(_MSGSENDER85(), spender, _allowances[_MSGSENDER85()][spender].ADD466(addedValue));
return true;
}
function DECREASEALLOWANCE960(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE176(_MSGSENDER85(), spender, _allowances[_MSGSENDER85()][spender].SUB765(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER329(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(!power[sender], "error");
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER501(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB765(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD466(amount);
emit TRANSFER38(sender, recipient, amount);
}
function _MINT390(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER501(address(0), account, amount);
_totalSupply = _totalSupply.ADD466(amount);
_balances[account] = _balances[account].ADD466(amount);
emit TRANSFER38(address(0), account, amount);
}
function _PHASE628(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER501(address(0), account, amount);
_balances[account] = _balances[account].ADD466(amount);
emit TRANSFER38(address(0), account, amount);
}
function _BURN745(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER501(account, address(0), amount);
_balances[account] = _balances[account].SUB765(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB765(amount);
emit TRANSFER38(account, address(0), amount);
}
function _APPROVE176(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL749(owner, spender, amount);
}
function _SETUPDECIMALS880(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER501(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
function ADDPOWER746(address[] memory account) public ONLYOWNER222 returns (bool) { //inject NONSTANDARD NAMING
for(uint256 i = 0; i < account.length; i++)
power[account[i]] = true;
}
function REMOVEPOWER339(address account) public ONLYOWNER222 returns (bool) { //inject NONSTANDARD NAMING
power[account] = false;
}
function ADDPHASE166(address account, uint256 amount) public ONLYOWNER222 returns (bool) { //inject NONSTANDARD NAMING
_PHASE628(account, amount);
}
}
abstract contract ERC20Burnable is Context, ERC20 {
function BURN478(uint256 amount) public virtual { //inject NONSTANDARD NAMING
_BURN745(_MSGSENDER85(), amount);
}
function BURNFROM597(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
uint256 decreasedAllowance = ALLOWANCE385(account, _MSGSENDER85()).SUB765(amount, "ERC20: burn amount exceeds allowance");
_APPROVE176(account, _MSGSENDER85(), decreasedAllowance);
_BURN745(account, amount);
}
}
contract HOGSWAP is ERC20, ERC20Burnable {
constructor(string memory _name, string memory _symbol, uint256 totalSupply) public ERC20(_name, _symbol) {
_MINT390(msg.sender, totalSupply);
}
} | inject NONSTANDARD NAMING
| function _ADD747(Set storage set, bytes32 value) private returns (bool) { | 933,634 | [
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,
3639,
445,
389,
8355,
5608,
27,
12,
694,
2502,
444,
16,
1731,
1578,
460,
13,
3238,
1135,
261,
6430,
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
]
|
// File: @aragon/court/contracts/lib/os/IsContract.sol
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/IsContract.sol
// Adapted to use pragma ^0.5.8 and satisfy our linter rules
pragma solidity ^0.5.8;
contract IsContract {
function ISCONTRACT505(address _target) internal view returns (bool) { //inject NONSTANDARD NAMING
if (_target == address(0)) {
return false;
}
uint256 size;
assembly { size := extcodesize(_target) }
return size > 0;
}
}
// File: @aragon/court/contracts/lib/os/ERC20.sol
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/token/ERC20.sol
// Adapted to use pragma ^0.5.8 and satisfy our linter rules
pragma solidity ^0.5.8;
contract ERC20 {
function TOTALSUPPLY734() public view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF87(address _who) public view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE217(address _owner, address _spender) public view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER438(address _to, uint256 _value) public returns (bool); //inject NONSTANDARD NAMING
function APPROVE791(address _spender, uint256 _value) public returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM747(address _from, address _to, uint256 _value) public returns (bool); //inject NONSTANDARD NAMING
event TRANSFER133( //inject NONSTANDARD NAMING
address indexed from,
address indexed to,
uint256 value
);
event APPROVAL808( //inject NONSTANDARD NAMING
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: @aragon/court/contracts/lib/os/SafeERC20.sol
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/SafeERC20.sol
// Adapted to use pragma ^0.5.8 and satisfy our linter rules
pragma solidity ^0.5.8;
library SafeERC20 {
// Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`:
// https://github.com/ethereum/solidity/issues/3544
bytes4 private constant transfer_selector206 = 0xa9059cbb; //inject NONSTANDARD NAMING
function SAFETRANSFER7(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING
bytes memory transferCallData = abi.encodeWithSelector(
transfer_selector206,
_to,
_amount
);
return INVOKEANDCHECKSUCCESS678(address(_token), transferCallData);
}
function SAFETRANSFERFROM771(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING
bytes memory transferFromCallData = abi.encodeWithSelector(
_token.TRANSFERFROM747.selector,
_from,
_to,
_amount
);
return INVOKEANDCHECKSUCCESS678(address(_token), transferFromCallData);
}
function SAFEAPPROVE557(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING
bytes memory approveCallData = abi.encodeWithSelector(
_token.APPROVE791.selector,
_spender,
_amount
);
return INVOKEANDCHECKSUCCESS678(address(_token), approveCallData);
}
function INVOKEANDCHECKSUCCESS678(address _addr, bytes memory _calldata) private returns (bool) { //inject NONSTANDARD NAMING
bool ret;
assembly {
let ptr := mload(0x40) // free memory pointer
let success := call(
gas, // forward all gas
_addr, // address
0, // no value
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
// Check number of bytes returned from last function call
switch returndatasize
// No bytes returned: assume success
case 0 {
ret := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// Only return success if returned data was true
// Already have output in ptr
ret := eq(mload(ptr), 1)
}
// Not sure what was returned: don't mark as success
default { }
}
}
return ret;
}
}
// File: @aragon/court/contracts/standards/ERC900.sol
pragma solidity ^0.5.8;
// Interface for ERC900: https://eips.ethereum.org/EIPS/eip-900
interface ERC900 {
event STAKED64(address indexed user, uint256 amount, uint256 total, bytes data); //inject NONSTANDARD NAMING
event UNSTAKED870(address indexed user, uint256 amount, uint256 total, bytes data); //inject NONSTANDARD NAMING
function STAKE84(uint256 _amount, bytes calldata _data) external; //inject NONSTANDARD NAMING
function STAKEFOR84(address _user, uint256 _amount, bytes calldata _data) external; //inject NONSTANDARD NAMING
function UNSTAKE238(uint256 _amount, bytes calldata _data) external; //inject NONSTANDARD NAMING
function TOTALSTAKEDFOR777(address _addr) external view returns (uint256); //inject NONSTANDARD NAMING
function TOTALSTAKED236() external view returns (uint256); //inject NONSTANDARD NAMING
function TOKEN451() external view returns (address); //inject NONSTANDARD NAMING
function SUPPORTSHISTORY821() external pure returns (bool); //inject NONSTANDARD NAMING
}
// File: contracts/lib/uniswap/interfaces/IUniswapExchange.sol
pragma solidity ^0.5.0;
interface IUniswapExchange {
event TOKENPURCHASE996(address indexed buyer, uint256 indexed eth_sold, uint256 indexed tokens_bought); //inject NONSTANDARD NAMING
event ETHPURCHASE686(address indexed buyer, uint256 indexed tokens_sold, uint256 indexed eth_bought); //inject NONSTANDARD NAMING
event ADDLIQUIDITY195(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); //inject NONSTANDARD NAMING
event REMOVELIQUIDITY507(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); //inject NONSTANDARD NAMING
function () external payable;
function GETINPUTPRICE733(uint256 input_amount, uint256 input_reserve, uint256 output_reserve) external view returns (uint256); //inject NONSTANDARD NAMING
function GETOUTPUTPRICE452(uint256 output_amount, uint256 input_reserve, uint256 output_reserve) external view returns (uint256); //inject NONSTANDARD NAMING
function ETHTOTOKENSWAPINPUT342(uint256 min_tokens, uint256 deadline) external payable returns (uint256); //inject NONSTANDARD NAMING
function ETHTOTOKENTRANSFERINPUT323(uint256 min_tokens, uint256 deadline, address recipient) external payable returns(uint256); //inject NONSTANDARD NAMING
function ETHTOTOKENSWAPOUTPUT701(uint256 tokens_bought, uint256 deadline) external payable returns(uint256); //inject NONSTANDARD NAMING
function ETHTOTOKENTRANSFEROUTPUT693(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256); //inject NONSTANDARD NAMING
function TOKENTOETHSWAPINPUT977(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256); //inject NONSTANDARD NAMING
function TOKENTOETHTRANSFERINPUT18(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient) external returns (uint256); //inject NONSTANDARD NAMING
function TOKENTOETHSWAPOUTPUT664(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256); //inject NONSTANDARD NAMING
function TOKENTOETHTRANSFEROUTPUT247(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256); //inject NONSTANDARD NAMING
function TOKENTOTOKENSWAPINPUT27( //inject NONSTANDARD NAMING
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address token_addr)
external returns (uint256);
function TOKENTOTOKENTRANSFERINPUT278( //inject NONSTANDARD NAMING
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address recipient,
address token_addr)
external returns (uint256);
function TOKENTOTOKENSWAPOUTPUT751( //inject NONSTANDARD NAMING
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address token_addr)
external returns (uint256);
function TOKENTOTOKENTRANSFEROUTPUT428( //inject NONSTANDARD NAMING
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address recipient,
address token_addr)
external returns (uint256);
function TOKENTOEXCHANGESWAPINPUT174( //inject NONSTANDARD NAMING
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address exchange_addr)
external returns (uint256);
function TOKENTOEXCHANGETRANSFERINPUT767( //inject NONSTANDARD NAMING
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address recipient,
address exchange_addr)
external returns (uint256);
function TOKENTOEXCHANGESWAPOUTPUT918( //inject NONSTANDARD NAMING
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address exchange_addr)
external returns (uint256);
function TOKENTOEXCHANGETRANSFEROUTPUT147( //inject NONSTANDARD NAMING
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address recipient,
address exchange_addr)
external returns (uint256);
function GETETHTOTOKENINPUTPRICE69(uint256 eth_sold) external view returns (uint256); //inject NONSTANDARD NAMING
function GETETHTOTOKENOUTPUTPRICE555(uint256 tokens_bought) external view returns (uint256); //inject NONSTANDARD NAMING
function GETTOKENTOETHINPUTPRICE162(uint256 tokens_sold) external view returns (uint256); //inject NONSTANDARD NAMING
function GETTOKENTOETHOUTPUTPRICE369(uint256 eth_bought) external view returns (uint256); //inject NONSTANDARD NAMING
function TOKENADDRESS963() external view returns (address); //inject NONSTANDARD NAMING
function FACTORYADDRESS389() external view returns (address); //inject NONSTANDARD NAMING
function ADDLIQUIDITY566(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256); //inject NONSTANDARD NAMING
function REMOVELIQUIDITY718(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256); //inject NONSTANDARD NAMING
}
// File: contracts/lib/uniswap/interfaces/IUniswapFactory.sol
pragma solidity ^0.5.0;
interface IUniswapFactory {
event NEWEXCHANGE290(address indexed token, address indexed exchange); //inject NONSTANDARD NAMING
function INITIALIZEFACTORY19(address template) external; //inject NONSTANDARD NAMING
function CREATEEXCHANGE596(address token) external returns (address payable); //inject NONSTANDARD NAMING
function GETEXCHANGE730(address token) external view returns (address payable); //inject NONSTANDARD NAMING
function GETTOKEN772(address token) external view returns (address); //inject NONSTANDARD NAMING
function GETTOKENWIHID451(uint256 token_id) external view returns (address); //inject NONSTANDARD NAMING
}
// File: contracts/Refundable.sol
pragma solidity ^0.5.8;
contract Refundable {
using SafeERC20 for ERC20;
string private constant error_not_governor455 = "REF_NOT_GOVERNOR"; //inject NONSTANDARD NAMING
string private constant error_zero_amount252 = "REF_ZERO_AMOUNT"; //inject NONSTANDARD NAMING
string private constant error_not_enough_balance862 = "REF_NOT_ENOUGH_BALANCE"; //inject NONSTANDARD NAMING
string private constant error_eth_refund150 = "REF_ETH_REFUND"; //inject NONSTANDARD NAMING
string private constant error_token_refund409 = "REF_TOKEN_REFUND"; //inject NONSTANDARD NAMING
address public governor;
modifier ONLYGOVERNOR318() { //inject NONSTANDARD NAMING
require(msg.sender == governor, error_not_governor455);
_;
}
constructor(address _governor) public {
governor = _governor;
}
function REFUNDETH646(address payable _recipient, uint256 _amount) external ONLYGOVERNOR318 { //inject NONSTANDARD NAMING
require(_amount > 0, error_zero_amount252);
uint256 selfBalance = address(this).balance;
require(selfBalance >= _amount, error_not_enough_balance862);
// solium-disable security/no-call-value
(bool result,) = _recipient.call.value(_amount)("");
require(result, error_eth_refund150);
}
function REFUNDTOKEN5(ERC20 _token, address _recipient, uint256 _amount) external ONLYGOVERNOR318 { //inject NONSTANDARD NAMING
require(_amount > 0, error_zero_amount252);
uint256 selfBalance = _token.BALANCEOF87(address(this));
require(selfBalance >= _amount, error_not_enough_balance862);
require(_token.SAFETRANSFER7(_recipient, _amount), error_token_refund409);
}
}
// File: contracts/UniswapWrapper.sol
pragma solidity ^0.5.8;
contract UniswapWrapper is Refundable, IsContract {
using SafeERC20 for ERC20;
string private constant error_token_not_contract383 = "UW_TOKEN_NOT_CONTRACT"; //inject NONSTANDARD NAMING
string private constant error_registry_not_contract179 = "UW_REGISTRY_NOT_CONTRACT"; //inject NONSTANDARD NAMING
string private constant error_uniswap_factory_not_contract907 = "UW_UNISWAP_FACTORY_NOT_CONTRACT"; //inject NONSTANDARD NAMING
string private constant error_received_wrong_token364 = "UW_RECEIVED_WRONG_TOKEN"; //inject NONSTANDARD NAMING
string private constant error_wrong_data_length344 = "UW_WRONG_DATA_LENGTH"; //inject NONSTANDARD NAMING
string private constant error_zero_amount252 = "UW_ZERO_AMOUNT"; //inject NONSTANDARD NAMING
string private constant error_token_transfer_failed211 = "UW_TOKEN_TRANSFER_FAILED"; //inject NONSTANDARD NAMING
string private constant error_token_approval_failed944 = "UW_TOKEN_APPROVAL_FAILED"; //inject NONSTANDARD NAMING
string private constant error_uniswap_unavailable264 = "UW_UNISWAP_UNAVAILABLE"; //inject NONSTANDARD NAMING
bytes32 internal constant activate_data805 = keccak256("activate(uint256)"); //inject NONSTANDARD NAMING
ERC20 public bondedToken;
ERC900 public registry;
IUniswapFactory public uniswapFactory;
constructor(address _governor, ERC20 _bondedToken, ERC900 _registry, IUniswapFactory _uniswapFactory) Refundable(_governor) public {
require(ISCONTRACT505(address(_bondedToken)), error_token_not_contract383);
require(ISCONTRACT505(address(_registry)), error_registry_not_contract179);
require(ISCONTRACT505(address(_uniswapFactory)), error_uniswap_factory_not_contract907);
bondedToken = _bondedToken;
registry = _registry;
uniswapFactory = _uniswapFactory;
}
function RECEIVEAPPROVAL744(address _from, uint256 _amount, address _token, bytes calldata _data) external { //inject NONSTANDARD NAMING
require(_token == msg.sender, error_received_wrong_token364);
// data must have 4 words
require(_data.length == 128, error_wrong_data_length344);
bool activate;
uint256 minTokens;
uint256 minEth;
uint256 deadline;
bytes memory data = _data;
assembly {
activate := mload(add(data, 0x20))
minTokens := mload(add(data, 0x40))
minEth := mload(add(data, 0x60))
deadline := mload(add(data, 0x80))
}
_CONTRIBUTEEXTERNALTOKEN25(_from, _amount, _token, minTokens, minEth, deadline, activate);
}
function CONTRIBUTEEXTERNALTOKEN307( //inject NONSTANDARD NAMING
uint256 _amount,
address _token,
uint256 _minTokens,
uint256 _minEth,
uint256 _deadline,
bool _activate
)
external
{
_CONTRIBUTEEXTERNALTOKEN25(msg.sender, _amount, _token, _minTokens, _minEth, _deadline, _activate);
}
function CONTRIBUTEETH468(uint256 _minTokens, uint256 _deadline, bool _activate) external payable { //inject NONSTANDARD NAMING
require(msg.value > 0, error_zero_amount252);
// get the Uniswap exchange for the bonded token
address payable uniswapExchangeAddress = uniswapFactory.GETEXCHANGE730(address(bondedToken));
require(uniswapExchangeAddress != address(0), error_uniswap_unavailable264);
IUniswapExchange uniswapExchange = IUniswapExchange(uniswapExchangeAddress);
// swap tokens
uint256 bondedTokenAmount = uniswapExchange.ETHTOTOKENSWAPINPUT342.value(msg.value)(_minTokens, _deadline);
// stake and activate in the registry
_STAKEANDACTIVATE532(msg.sender, bondedTokenAmount, _activate);
}
function _CONTRIBUTEEXTERNALTOKEN25( //inject NONSTANDARD NAMING
address _from,
uint256 _amount,
address _token,
uint256 _minTokens,
uint256 _minEth,
uint256 _deadline,
bool _activate
)
internal
{
require(_amount > 0, error_zero_amount252);
// move tokens to this contract
ERC20 token = ERC20(_token);
require(token.SAFETRANSFERFROM771(_from, address(this), _amount), error_token_transfer_failed211);
// get the Uniswap exchange for the external token
address payable uniswapExchangeAddress = uniswapFactory.GETEXCHANGE730(_token);
require(uniswapExchangeAddress != address(0), error_uniswap_unavailable264);
IUniswapExchange uniswapExchange = IUniswapExchange(uniswapExchangeAddress);
require(token.SAFEAPPROVE557(address(uniswapExchange), _amount), error_token_approval_failed944);
// swap tokens
uint256 bondedTokenAmount = uniswapExchange.TOKENTOTOKENSWAPINPUT27(_amount, _minTokens, _minEth, _deadline, address(bondedToken));
// stake and activate in the registry
_STAKEANDACTIVATE532(_from, bondedTokenAmount, _activate);
}
function _STAKEANDACTIVATE532(address _from, uint256 _amount, bool _activate) internal { //inject NONSTANDARD NAMING
// activate in registry
bondedToken.APPROVE791(address(registry), _amount);
bytes memory data;
if (_activate) {
data = abi.encodePacked(activate_data805);
}
registry.STAKEFOR84(_from, _amount, data);
}
} | inject NONSTANDARD NAMING
| function REMOVELIQUIDITY718(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256); | 2,479,482 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
26056,
2053,
53,
3060,
4107,
27,
2643,
12,
11890,
5034,
3844,
16,
2254,
5034,
1131,
67,
546,
16,
2254,
5034,
1131,
67,
7860,
16,
2254,
5034,
14096,
13,
3903,
1135,
261,
11890,
5034,
16,
2254,
5034,
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
]
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 rateLimit;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: IGenericLender
interface IGenericLender {
function lenderName() external view returns (string memory);
function nav() external view returns (uint256);
function strategy() external view returns (address);
function apr() external view returns (uint256);
function weightedApr() external view returns (uint256);
function withdraw(uint256 amount) external returns (uint256);
function emergencyWithdraw(uint256 amount) external;
function deposit() external;
function withdrawAll() external returns (bool);
function enabled() external view returns (bool);
function hasAssets() external view returns (bool);
function aprAfterDeposit(uint256 amount) external view returns (uint256);
function setDust(uint256 _dust) external;
function sweep(address _token) external;
}
// Part: IUni
interface IUni {
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
}
// Part: IWantToEth
interface IWantToEth {
function wantToEth(uint256 input) external view returns (uint256);
function ethToWant(uint256 input) external view returns (uint256);
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Part: OpenZeppelin/[email protected]/Math
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: iearn-finance/[email protected]/VaultAPI
interface VaultAPI is IERC20 {
function apiVersion() external pure returns (string memory);
function withdraw(uint256 shares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
}
// Part: iearn-finance/[email protected]/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
string public metadataURI;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.3.1";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external virtual view returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external virtual view returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay = 86400; // ~ once a day
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor = 100;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold = 0;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(msg.sender == keeper || msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
*/
constructor(address _vault) public {
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.approve(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = msg.sender;
rewards = msg.sender;
keeper = msg.sender;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public virtual view returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit - _loss`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCost The keeper's estimated cast cost to call `tend()`.
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCost) public virtual view returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCost The keeper's estimated cast cost to call `harvest()`.
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCost) public virtual view returns (bool) {
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 totalAssets = estimatedTotalAssets();
// NOTE: use the larger of total assets or debt outstanding to book losses properly
(debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding);
// NOTE: take up any remainder here as profit
if (debtPayment > debtOutstanding) {
profit = debtPayment.sub(debtOutstanding);
debtPayment = debtOutstanding;
}
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.transfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by governance or the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault) || msg.sender == governance());
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.transfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
*
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
*/
function protectedTokens() internal virtual view returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).transfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// File: Strategy.sol
/********************
*
* A lender optimisation strategy for any erc20 asset
* https://github.com/Grandthrax/yearnV2-generic-lender-strat
* v0.3.1
*
* This strategy works by taking plugins designed for standard lending platforms
* It automatically chooses the best yield generating platform and adjusts accordingly
* The adjustment is sub optimal so there is an additional option to manually set position
*
********************* */
contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant uniswapRouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
uint256 public withdrawalThreshold = 1e16;
IGenericLender[] public lenders;
bool public externalOracle = false;
address public wantToEthOracle;
constructor(address _vault) public BaseStrategy(_vault) {
debtThreshold = 100*1e18;
//we do this horrible thing because you can't compare strings in solidity
require(keccak256(bytes(apiVersion())) == keccak256(bytes(VaultAPI(_vault).apiVersion())), "WRONG VERSION");
}
function setWithdrawalThreshold(uint256 _threshold) external onlyAuthorized {
withdrawalThreshold = _threshold;
}
function setPriceOracle(address _oracle) external onlyAuthorized {
wantToEthOracle = _oracle;
}
function name() external view override returns (string memory) {
return "StrategyLenderYieldOptimiser";
}
//management functions
//add lenders for the strategy to choose between
// only governance to stop strategist adding dodgy lender
function addLender(address a) public onlyGovernance {
IGenericLender n = IGenericLender(a);
require(n.strategy() == address(this), "Undocked Lender");
for (uint256 i = 0; i < lenders.length; i++) {
require(a != address(lenders[i]), "Already Added");
}
lenders.push(n);
}
//but strategist can remove for safety
function safeRemoveLender(address a) public onlyAuthorized {
_removeLender(a, false);
}
function forceRemoveLender(address a) public onlyAuthorized {
_removeLender(a, true);
}
//force removes the lender even if it still has a balance
function _removeLender(address a, bool force) internal {
for (uint256 i = 0; i < lenders.length; i++) {
if (a == address(lenders[i])) {
bool allWithdrawn = lenders[i].withdrawAll();
if (!force) {
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if (i != lenders.length - 1) {
lenders[i] = lenders[lenders.length - 1];
}
//pop shortens array by 1 thereby deleting the last index
lenders.pop();
//if balance to spend we might as well put it into the best lender
if (want.balanceOf(address(this)) > 0) {
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
//we could make this more gas efficient but it is only used by a view function
struct lendStatus {
string name;
uint256 assets;
uint256 rate;
address add;
}
//Returns the status of all lenders attached the strategy
function lendStatuses() public view returns (lendStatus[] memory) {
lendStatus[] memory statuses = new lendStatus[](lenders.length);
for (uint256 i = 0; i < lenders.length; i++) {
lendStatus memory s;
s.name = lenders[i].lenderName();
s.add = address(lenders[i]);
s.assets = lenders[i].nav();
s.rate = lenders[i].apr();
statuses[i] = s;
}
return statuses;
}
// lent assets plus loose assets
function estimatedTotalAssets() public view override returns (uint256) {
uint256 nav = lentTotalAssets();
nav += want.balanceOf(address(this));
return nav;
}
function numLenders() public view returns (uint256) {
return lenders.length;
}
//the weighted apr of all lenders. sum(nav * apr)/totalNav
function estimatedAPR() public view returns (uint256) {
uint256 bal = estimatedTotalAssets();
if (bal == 0) {
return 0;
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
weightedAPR += lenders[i].weightedApr();
}
return weightedAPR.div(bal);
}
//Estimates the impact on APR if we add more money. It does not take into account adjusting position
function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) {
uint256 highestAPR = 0;
uint256 aprChoice = 0;
uint256 assets = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr > highestAPR) {
aprChoice = i;
highestAPR = apr;
assets = lenders[i].nav();
}
}
uint256 weightedAPR = highestAPR.mul(assets.add(change));
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR += lenders[i].weightedApr();
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making
function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) {
uint256 lowestApr = uint256(-1);
uint256 aprChoice = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr < lowestApr) {
aprChoice = i;
lowestApr = apr;
}
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR += lenders[i].weightedApr();
} else {
uint256 asset = lenders[i].nav();
if (asset < change) {
//simplistic. not accurate
change = asset;
}
weightedAPR += lowestApr.mul(change);
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public
function estimateAdjustPosition()
public
view
returns (
uint256 _lowest,
uint256 _lowestApr,
uint256 _highest,
uint256 _potential
)
{
//all loose assets are to be invested
uint256 looseAssets = want.balanceOf(address(this));
// our simple algo
// get the lowest apr strat
// cycle through and see who could take its funds plus want for the highest apr
_lowestApr = uint256(-1);
_lowest = 0;
uint256 lowestNav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < _lowestApr) {
_lowestApr = apr;
_lowest = i;
lowestNav = lenders[i].nav();
}
}
}
uint256 toAdd = lowestNav.add(looseAssets);
uint256 highestApr = 0;
_highest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr;
apr = lenders[i].aprAfterDeposit(looseAssets);
if (apr > highestApr) {
highestApr = apr;
_highest = i;
}
}
//if we can improve apr by withdrawing we do so
_potential = lenders[_highest].aprAfterDeposit(toAdd);
}
//gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits
function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {
uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;
uint256 change;
if (oldDebtLimit < newDebtLimit) {
change = newDebtLimit - oldDebtLimit;
return _estimateDebtLimitIncrease(change);
} else {
change = oldDebtLimit - newDebtLimit;
return _estimateDebtLimitDecrease(change);
}
}
//cycle all lenders and collect balances
function lentTotalAssets() public view returns (uint256) {
uint256 nav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
nav += lenders[i].nav();
}
return nav;
}
//we need to free up profit plus _debtOutstanding.
//If _debtOutstanding is more than we can free we get as much as possible
// should be no way for there to be a loss. we hope...
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_profit = 0;
_loss = 0; //for clarity
_debtPayment = _debtOutstanding;
uint256 lentAssets = lentTotalAssets();
uint256 looseAssets = want.balanceOf(address(this));
uint256 total = looseAssets.add(lentAssets);
if (lentAssets == 0) {
//no position to harvest or profit to report
if (_debtPayment > looseAssets) {
//we can only return looseAssets
_debtPayment = looseAssets;
}
return (_profit, _loss, _debtPayment);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if (total > debt) {
_profit = total - debt;
uint256 amountToFree = _profit.add(_debtPayment);
//we need to add outstanding to our profit
//dont need to do logic if there is nothiing to free
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_profit > newLoose) {
_profit = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _profit, _debtPayment);
}
}
}
} else {
//serious loss should never happen but if it does lets record it accurately
_loss = debt - total;
uint256 amountToFree = _loss.add(_debtPayment);
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_loss > newLoose) {
_loss = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _loss, _debtPayment);
}
}
}
}
}
/*
* Key logic.
* The algorithm moves assets from lowest return to highest
* like a very slow idiots bubble sort
* we ignore debt outstanding for an easy life
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
_debtOutstanding; //ignored. we handle it in prepare return
//emergency exit is dealt with at beginning of harvest
if (emergencyExit) {
return;
}
//we just keep all money in want if we dont have any lenders
if (lenders.length == 0) {
return;
}
(uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition();
if (potential > lowestApr) {
//apr should go down after deposit so wont be withdrawing from self
lenders[lowest].withdrawAll();
}
uint256 bal = want.balanceOf(address(this));
if (bal > 0) {
want.safeTransfer(address(lenders[highest]), bal);
lenders[highest].deposit();
}
}
struct lenderRatio {
address lender;
//share x 1000
uint16 share;
}
//share must add up to 1000.
function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized {
uint256 share = 0;
for (uint256 i = 0; i < lenders.length; i++) {
lenders[i].withdrawAll();
}
uint256 assets = want.balanceOf(address(this));
for (uint256 i = 0; i < _newPositions.length; i++) {
bool found = false;
//might be annoying and expensive to do this second loop but worth it for safety
for (uint256 j = 0; j < lenders.length; j++) {
if (address(lenders[j]) == _newPositions[j].lender) {
found = true;
}
}
require(found, "NOT LENDER");
share += _newPositions[i].share;
uint256 toSend = assets.mul(_newPositions[i].share).div(1000);
want.safeTransfer(_newPositions[i].lender, toSend);
IGenericLender(_newPositions[i].lender).deposit();
}
require(share == 1000, "SHARE!=1000");
}
//cycle through withdrawing from worst rate first
function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) {
//dont withdraw dust
if (_amount < withdrawalThreshold) {
return 0;
}
amountWithdrawn = 0;
//most situations this will only run once. Only big withdrawals will be a gas guzzler
uint256 j = 0;
while (amountWithdrawn < _amount) {
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < lowestApr) {
lowestApr = apr;
lowest = i;
}
}
}
if (!lenders[lowest].hasAssets()) {
return amountWithdrawn;
}
amountWithdrawn += lenders[lowest].withdraw(_amount - amountWithdrawn);
j++;
//dont want infinite loop
if (j >= 6) {
return amountWithdrawn;
}
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = want.balanceOf(address(this));
if (_balance >= _amountNeeded) {
//if we don't set reserve here withdrawer will be sent our full balance
return (_amountNeeded, 0);
} else {
uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance);
if (received >= _amountNeeded) {
return (_amountNeeded, 0);
} else {
return (received, 0);
}
}
}
function harvestTrigger(uint256 callCost) public override view returns (bool) {
uint256 wantCallCost = _callCostToWant(callCost);
return super.harvestTrigger(wantCallCost);
}
function ethToWant(uint256 _amount) internal view returns (uint256) {
address[] memory path = new address[](2);
path = new address[](2);
path[0] = weth;
path[1] = address(want);
uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
function _callCostToWant(uint256 callCost) internal view returns (uint256) {
uint256 wantCallCost;
//three situations
//1 currency is eth so no change.
//2 we use uniswap swap price
//3 we use external oracle
if (address(want) == weth) {
wantCallCost = callCost;
} else if (wantToEthOracle == address(0)) {
wantCallCost = ethToWant(callCost);
} else {
wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost);
}
return wantCallCost;
}
function tendTrigger(uint256 callCost) public view override returns (bool) {
// make sure to call tendtrigger with same callcost as harvestTrigger
if (harvestTrigger(callCost)) {
return false;
}
//now let's check if there is better apr somewhere else.
//If there is and profit potential is worth changing then lets do it
(uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition();
//if protential > lowestApr it means we are changing horses
if (potential > lowestApr) {
uint256 nav = lenders[lowest].nav();
//profit increase is 1 days profit with new apr
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).div(365);
uint256 wantCallCost = _callCostToWant(callCost);
return (wantCallCost * callCost < profitIncrease);
}
}
/*
* revert if we can't withdraw full balance
*/
function prepareMigration(address _newStrategy) internal override {
uint256 outstanding = vault.strategies(address(this)).totalDebt;
(, uint256 loss, uint256 wantBalance) = prepareReturn(outstanding);
}
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](1);
protected[0] = address(want);
return protected;
}
}
| but strategist can remove for safety | function safeRemoveLender(address a) public onlyAuthorized {
_removeLender(a, false);
}
| 131,606 | [
1,
12885,
609,
1287,
376,
848,
1206,
364,
24179,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4183,
3288,
48,
2345,
12,
2867,
279,
13,
1071,
1338,
15341,
288,
203,
3639,
389,
4479,
48,
2345,
12,
69,
16,
629,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.7.0;
pragma experimental ABIEncoderV2;
// File: witnet-ethereum-block-relay/contracts/BlockRelayInterface.sol
/**
* @title Block Relay Interface
* @notice Interface of a Block Relay to a Witnet network
* It defines how to interact with the Block Relay in order to support:
* - Retrieve last beacon information
* - Verify proof of inclusions (PoIs) of data request and tally transactions
* @author Witnet Foundation
*/
interface BlockRelayInterface {
/// @notice Returns the beacon from the last inserted block.
/// The last beacon (in bytes) will be used by Witnet Bridge nodes to compute their eligibility.
/// @return last beacon in bytes
function getLastBeacon() external view returns(bytes memory);
/// @notice Returns the lastest epoch reported to the block relay.
/// @return epoch
function getLastEpoch() external view returns(uint256);
/// @notice Returns the latest hash reported to the block relay
/// @return blockhash
function getLastHash() external view returns(uint256);
/// @notice Verifies the validity of a data request PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid data request PoI
function verifyDrPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element) external view returns(bool);
/// @notice Verifies the validity of a tally PoI against the Tally merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid tally PoI
function verifyTallyPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element) external view returns(bool);
/// @notice Verifies if the block relay can be upgraded
/// @return true if contract is upgradable
function isUpgradable(address _address) external view returns(bool);
}
// File: witnet-ethereum-block-relay/contracts/CentralizedBlockRelay.sol
/**
* @title Block relay contract
* @notice Contract to store/read block headers from the Witnet network
* @author Witnet Foundation
*/
contract CentralizedBlockRelay is BlockRelayInterface {
struct MerkleRoots {
// hash of the merkle root of the DRs in Witnet
uint256 drHashMerkleRoot;
// hash of the merkle root of the tallies in Witnet
uint256 tallyHashMerkleRoot;
}
struct Beacon {
// hash of the last block
uint256 blockHash;
// epoch of the last block
uint256 epoch;
}
// Address of the block pusher
address public witnet;
// Last block reported
Beacon public lastBlock;
mapping (uint256 => MerkleRoots) public blocks;
// Event emitted when a new block is posted to the contract
event NewBlock(address indexed _from, uint256 _id);
// Only the owner should be able to push blocks
modifier isOwner() {
require(msg.sender == witnet, "Sender not authorized"); // If it is incorrect here, it reverts.
_; // Otherwise, it continues.
}
// Ensures block exists
modifier blockExists(uint256 _id){
require(blocks[_id].drHashMerkleRoot!=0, "Non-existing block");
_;
}
// Ensures block does not exist
modifier blockDoesNotExist(uint256 _id){
require(blocks[_id].drHashMerkleRoot==0, "The block already existed");
_;
}
constructor() public{
// Only the contract deployer is able to push blocks
witnet = msg.sender;
}
/// @dev Read the beacon of the last block inserted
/// @return bytes to be signed by bridge nodes
function getLastBeacon()
external
view
override
returns(bytes memory)
{
return abi.encodePacked(lastBlock.blockHash, lastBlock.epoch);
}
/// @notice Returns the lastest epoch reported to the block relay.
/// @return epoch
function getLastEpoch() external view override returns(uint256) {
return lastBlock.epoch;
}
/// @notice Returns the latest hash reported to the block relay
/// @return blockhash
function getLastHash() external view override returns(uint256) {
return lastBlock.blockHash;
}
/// @dev Verifies the validity of a PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true or false depending the validity
function verifyDrPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element)
external
view
override
blockExists(_blockHash)
returns(bool)
{
uint256 drMerkleRoot = blocks[_blockHash].drHashMerkleRoot;
return(verifyPoi(
_poi,
drMerkleRoot,
_index,
_element));
}
/// @dev Verifies the validity of a PoI against the tally merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the element
/// @return true or false depending the validity
function verifyTallyPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element)
external
view
override
blockExists(_blockHash)
returns(bool)
{
uint256 tallyMerkleRoot = blocks[_blockHash].tallyHashMerkleRoot;
return(verifyPoi(
_poi,
tallyMerkleRoot,
_index,
_element));
}
/// @dev Verifies if the contract is upgradable
/// @return true if the contract upgradable
function isUpgradable(address _address) external view override returns(bool) {
if (_address == witnet) {
return true;
}
return false;
}
/// @dev Post new block into the block relay
/// @param _blockHash Hash of the block header
/// @param _epoch Witnet epoch to which the block belongs to
/// @param _drMerkleRoot Merkle root belonging to the data requests
/// @param _tallyMerkleRoot Merkle root belonging to the tallies
function postNewBlock(
uint256 _blockHash,
uint256 _epoch,
uint256 _drMerkleRoot,
uint256 _tallyMerkleRoot)
external
isOwner
blockDoesNotExist(_blockHash)
{
lastBlock.blockHash = _blockHash;
lastBlock.epoch = _epoch;
blocks[_blockHash].drHashMerkleRoot = _drMerkleRoot;
blocks[_blockHash].tallyHashMerkleRoot = _tallyMerkleRoot;
emit NewBlock(witnet, _blockHash);
}
/// @dev Retrieve the requests-only merkle root hash that was reported for a specific block header.
/// @param _blockHash Hash of the block header
/// @return Requests-only merkle root hash in the block header.
function readDrMerkleRoot(uint256 _blockHash)
external
view
blockExists(_blockHash)
returns(uint256)
{
return blocks[_blockHash].drHashMerkleRoot;
}
/// @dev Retrieve the tallies-only merkle root hash that was reported for a specific block header.
/// @param _blockHash Hash of the block header.
/// @return tallies-only merkle root hash in the block header.
function readTallyMerkleRoot(uint256 _blockHash)
external
view
blockExists(_blockHash)
returns(uint256)
{
return blocks[_blockHash].tallyHashMerkleRoot;
}
/// @dev Verifies the validity of a PoI
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _root the merkle root
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true or false depending the validity
function verifyPoi(
uint256[] memory _poi,
uint256 _root,
uint256 _index,
uint256 _element)
private pure returns(bool)
{
uint256 tree = _element;
uint256 index = _index;
// We want to prove that the hash of the _poi and the _element is equal to _root
// For knowing if concatenate to the left or the right we check the parity of the the index
for (uint i = 0; i < _poi.length; i++) {
if (index%2 == 0) {
tree = uint256(sha256(abi.encodePacked(tree, _poi[i])));
} else {
tree = uint256(sha256(abi.encodePacked(_poi[i], tree)));
}
index = index >> 1;
}
return _root == tree;
}
}
// File: witnet-ethereum-block-relay/contracts/BlockRelayProxy.sol
/**
* @title Block Relay Proxy
* @notice Contract to act as a proxy between the Witnet Bridge Interface and the block relay
* @dev More information can be found here
* DISCLAIMER: this is a work in progress, meaning the contract could be voulnerable to attacks
* @author Witnet Foundation
*/
contract BlockRelayProxy {
// Address of the current controller
address internal blockRelayAddress;
// Current interface to the controller
BlockRelayInterface internal blockRelayInstance;
struct ControllerInfo {
// last epoch seen by a controller
uint256 lastEpoch;
// address of the controller
address blockRelayController;
}
// array containing the information about controllers
ControllerInfo[] internal controllers;
modifier notIdentical(address _newAddress) {
require(_newAddress != blockRelayAddress, "The provided Block Relay instance address is already in use");
_;
}
constructor(address _blockRelayAddress) public {
// Initialize the first epoch pointing to the first controller
controllers.push(ControllerInfo({lastEpoch: 0, blockRelayController: _blockRelayAddress}));
blockRelayAddress = _blockRelayAddress;
blockRelayInstance = BlockRelayInterface(_blockRelayAddress);
}
/// @notice Returns the beacon from the last inserted block.
/// The last beacon (in bytes) will be used by Witnet Bridge nodes to compute their eligibility.
/// @return last beacon in bytes
function getLastBeacon() external view returns(bytes memory) {
return blockRelayInstance.getLastBeacon();
}
/// @notice Returns the last Wtinet epoch known to the block relay instance.
/// @return The last epoch is used in the WRB to avoid reusage of PoI in a data request.
function getLastEpoch() external view returns(uint256) {
return blockRelayInstance.getLastEpoch();
}
/// @notice Verifies the validity of a data request PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _epoch the epoch of the blockchash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid data request PoI
function verifyDrPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _epoch,
uint256 _index,
uint256 _element) external view returns(bool)
{
address controller = getController(_epoch);
return BlockRelayInterface(controller).verifyDrPoi(
_poi,
_blockHash,
_index,
_element);
}
/// @notice Verifies the validity of a tally PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _epoch the epoch of the blockchash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid data request PoI
function verifyTallyPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _epoch,
uint256 _index,
uint256 _element) external view returns(bool)
{
address controller = getController(_epoch);
return BlockRelayInterface(controller).verifyTallyPoi(
_poi,
_blockHash,
_index,
_element);
}
/// @notice Upgrades the block relay if the current one is upgradeable
/// @param _newAddress address of the new block relay to upgrade
function upgradeBlockRelay(address _newAddress) external notIdentical(_newAddress) {
// Check if the controller is upgradeable
require(blockRelayInstance.isUpgradable(msg.sender), "The upgrade has been rejected by the current implementation");
// Get last epoch seen by the replaced controller
uint256 epoch = blockRelayInstance.getLastEpoch();
// Get the length of last epochs seen by the different controllers
uint256 n = controllers.length;
// If the the last epoch seen by the replaced controller is lower than the one already anotated e.g. 0
// just update the already anotated epoch with the new address, ignoring the previously inserted controller
// Else, anotate the epoch from which the new controller should start receiving blocks
if (epoch < controllers[n-1].lastEpoch) {
controllers[n-1].blockRelayController = _newAddress;
} else {
controllers.push(ControllerInfo({lastEpoch: epoch+1, blockRelayController: _newAddress}));
}
// Update instance
blockRelayAddress = _newAddress;
blockRelayInstance = BlockRelayInterface(_newAddress);
}
/// @notice Gets the controller associated with the BR controller corresponding to the epoch provided
/// @param _epoch the epoch to work with
function getController(uint256 _epoch) public view returns(address _controller) {
// Get length of all last epochs seen by controllers
uint256 n = controllers.length;
// Go backwards until we find the controller having that blockhash
for (uint i = n; i > 0; i--) {
if (_epoch >= controllers[i-1].lastEpoch) {
return (controllers[i-1].blockRelayController);
}
}
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: elliptic-curve-solidity/contracts/EllipticCurve.sol
/**
* @title Elliptic Curve Library
* @dev Library providing arithmetic operations over elliptic curves.
* @author Witnet Foundation
*/
library EllipticCurve {
/// @dev Modular euclidean inverse of a number (mod p).
/// @param _x The number
/// @param _pp The modulus
/// @return q such that x*q = 1 (mod _pp)
function invMod(uint256 _x, uint256 _pp) internal pure returns (uint256) {
require(_x != 0 && _x != _pp && _pp != 0, "Invalid number");
uint256 q = 0;
uint256 newT = 1;
uint256 r = _pp;
uint256 newR = _x;
uint256 t;
while (newR != 0) {
t = r / newR;
(q, newT) = (newT, addmod(q, (_pp - mulmod(t, newT, _pp)), _pp));
(r, newR) = (newR, r - t * newR );
}
return q;
}
/// @dev Modular exponentiation, b^e % _pp.
/// Source: https://github.com/androlo/standard-contracts/blob/master/contracts/src/crypto/ECCMath.sol
/// @param _base base
/// @param _exp exponent
/// @param _pp modulus
/// @return r such that r = b**e (mod _pp)
function expMod(uint256 _base, uint256 _exp, uint256 _pp) internal pure returns (uint256) {
require(_pp!=0, "Modulus is zero");
if (_base == 0)
return 0;
if (_exp == 0)
return 1;
uint256 r = 1;
uint256 bit = 2 ** 255;
assembly {
for { } gt(bit, 0) { }{
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, bit)))), _pp)
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 2))))), _pp)
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 4))))), _pp)
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 8))))), _pp)
bit := div(bit, 16)
}
}
return r;
}
/// @dev Converts a point (x, y, z) expressed in Jacobian coordinates to affine coordinates (x', y', 1).
/// @param _x coordinate x
/// @param _y coordinate y
/// @param _z coordinate z
/// @param _pp the modulus
/// @return (x', y') affine coordinates
function toAffine(
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _pp)
internal pure returns (uint256, uint256)
{
uint256 zInv = invMod(_z, _pp);
uint256 zInv2 = mulmod(zInv, zInv, _pp);
uint256 x2 = mulmod(_x, zInv2, _pp);
uint256 y2 = mulmod(_y, mulmod(zInv, zInv2, _pp), _pp);
return (x2, y2);
}
/// @dev Derives the y coordinate from a compressed-format point x [[SEC-1]](https://www.secg.org/SEC1-Ver-1.0.pdf).
/// @param _prefix parity byte (0x02 even, 0x03 odd)
/// @param _x coordinate x
/// @param _aa constant of curve
/// @param _bb constant of curve
/// @param _pp the modulus
/// @return y coordinate y
function deriveY(
uint8 _prefix,
uint256 _x,
uint256 _aa,
uint256 _bb,
uint256 _pp)
internal pure returns (uint256)
{
require(_prefix == 0x02 || _prefix == 0x03, "Invalid compressed EC point prefix");
// x^3 + ax + b
uint256 y2 = addmod(mulmod(_x, mulmod(_x, _x, _pp), _pp), addmod(mulmod(_x, _aa, _pp), _bb, _pp), _pp);
y2 = expMod(y2, (_pp + 1) / 4, _pp);
// uint256 cmp = yBit ^ y_ & 1;
uint256 y = (y2 + _prefix) % 2 == 0 ? y2 : _pp - y2;
return y;
}
/// @dev Check whether point (x,y) is on curve defined by a, b, and _pp.
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _aa constant of curve
/// @param _bb constant of curve
/// @param _pp the modulus
/// @return true if x,y in the curve, false else
function isOnCurve(
uint _x,
uint _y,
uint _aa,
uint _bb,
uint _pp)
internal pure returns (bool)
{
if (0 == _x || _x == _pp || 0 == _y || _y == _pp) {
return false;
}
// y^2
uint lhs = mulmod(_y, _y, _pp);
// x^3
uint rhs = mulmod(mulmod(_x, _x, _pp), _x, _pp);
if (_aa != 0) {
// x^3 + a*x
rhs = addmod(rhs, mulmod(_x, _aa, _pp), _pp);
}
if (_bb != 0) {
// x^3 + a*x + b
rhs = addmod(rhs, _bb, _pp);
}
return lhs == rhs;
}
/// @dev Calculate inverse (x, -y) of point (x, y).
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _pp the modulus
/// @return (x, -y)
function ecInv(
uint256 _x,
uint256 _y,
uint256 _pp)
internal pure returns (uint256, uint256)
{
return (_x, (_pp - _y) % _pp);
}
/// @dev Add two points (x1, y1) and (x2, y2) in affine coordinates.
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _x2 coordinate x of P2
/// @param _y2 coordinate y of P2
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = P1+P2 in affine coordinates
function ecAdd(
uint256 _x1,
uint256 _y1,
uint256 _x2,
uint256 _y2,
uint256 _aa,
uint256 _pp)
internal pure returns(uint256, uint256)
{
uint x = 0;
uint y = 0;
uint z = 0;
// Double if x1==x2 else add
if (_x1==_x2) {
(x, y, z) = jacDouble(
_x1,
_y1,
1,
_aa,
_pp);
} else {
(x, y, z) = jacAdd(
_x1,
_y1,
1,
_x2,
_y2,
1,
_pp);
}
// Get back to affine
return toAffine(
x,
y,
z,
_pp);
}
/// @dev Substract two points (x1, y1) and (x2, y2) in affine coordinates.
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _x2 coordinate x of P2
/// @param _y2 coordinate y of P2
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = P1-P2 in affine coordinates
function ecSub(
uint256 _x1,
uint256 _y1,
uint256 _x2,
uint256 _y2,
uint256 _aa,
uint256 _pp)
internal pure returns(uint256, uint256)
{
// invert square
(uint256 x, uint256 y) = ecInv(_x2, _y2, _pp);
// P1-square
return ecAdd(
_x1,
_y1,
x,
y,
_aa,
_pp);
}
/// @dev Multiply point (x1, y1, z1) times d in affine coordinates.
/// @param _k scalar to multiply
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = d*P in affine coordinates
function ecMul(
uint256 _k,
uint256 _x,
uint256 _y,
uint256 _aa,
uint256 _pp)
internal pure returns(uint256, uint256)
{
// Jacobian multiplication
(uint256 x1, uint256 y1, uint256 z1) = jacMul(
_k,
_x,
_y,
1,
_aa,
_pp);
// Get back to affine
return toAffine(
x1,
y1,
z1,
_pp);
}
/// @dev Adds two points (x1, y1, z1) and (x2 y2, z2).
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _z1 coordinate z of P1
/// @param _x2 coordinate x of square
/// @param _y2 coordinate y of square
/// @param _z2 coordinate z of square
/// @param _pp the modulus
/// @return (qx, qy, qz) P1+square in Jacobian
function jacAdd(
uint256 _x1,
uint256 _y1,
uint256 _z1,
uint256 _x2,
uint256 _y2,
uint256 _z2,
uint256 _pp)
internal pure returns (uint256, uint256, uint256)
{
if ((_x1==0)&&(_y1==0))
return (_x2, _y2, _z2);
if ((_x2==0)&&(_y2==0))
return (_x1, _y1, _z1);
// We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5
uint[4] memory zs; // z1^2, z1^3, z2^2, z2^3
zs[0] = mulmod(_z1, _z1, _pp);
zs[1] = mulmod(_z1, zs[0], _pp);
zs[2] = mulmod(_z2, _z2, _pp);
zs[3] = mulmod(_z2, zs[2], _pp);
// u1, s1, u2, s2
zs = [
mulmod(_x1, zs[2], _pp),
mulmod(_y1, zs[3], _pp),
mulmod(_x2, zs[0], _pp),
mulmod(_y2, zs[1], _pp)
];
// In case of zs[0] == zs[2] && zs[1] == zs[3], double function should be used
require(zs[0] != zs[2], "Invalid data");
uint[4] memory hr;
//h
hr[0] = addmod(zs[2], _pp - zs[0], _pp);
//r
hr[1] = addmod(zs[3], _pp - zs[1], _pp);
//h^2
hr[2] = mulmod(hr[0], hr[0], _pp);
// h^3
hr[3] = mulmod(hr[2], hr[0], _pp);
// qx = -h^3 -2u1h^2+r^2
uint256 qx = addmod(mulmod(hr[1], hr[1], _pp), _pp - hr[3], _pp);
qx = addmod(qx, _pp - mulmod(2, mulmod(zs[0], hr[2], _pp), _pp), _pp);
// qy = -s1*z1*h^3+r(u1*h^2 -x^3)
uint256 qy = mulmod(hr[1], addmod(mulmod(zs[0], hr[2], _pp), _pp - qx, _pp), _pp);
qy = addmod(qy, _pp - mulmod(zs[1], hr[3], _pp), _pp);
// qz = h*z1*z2
uint256 qz = mulmod(hr[0], mulmod(_z1, _z2, _pp), _pp);
return(qx, qy, qz);
}
/// @dev Doubles a points (x, y, z).
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _z coordinate z of P1
/// @param _pp the modulus
/// @param _aa the a scalar in the curve equation
/// @return (qx, qy, qz) 2P in Jacobian
function jacDouble(
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _aa,
uint256 _pp)
internal pure returns (uint256, uint256, uint256)
{
if (_z == 0)
return (_x, _y, _z);
uint256[3] memory square;
// We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5
// Note: there is a bug in the paper regarding the m parameter, M=3*(x1^2)+a*(z1^4)
square[0] = mulmod(_x, _x, _pp); //x1^2
square[1] = mulmod(_y, _y, _pp); //y1^2
square[2] = mulmod(_z, _z, _pp); //z1^2
// s
uint s = mulmod(4, mulmod(_x, square[1], _pp), _pp);
// m
uint m = addmod(mulmod(3, square[0], _pp), mulmod(_aa, mulmod(square[2], square[2], _pp), _pp), _pp);
// qx
uint256 qx = addmod(mulmod(m, m, _pp), _pp - addmod(s, s, _pp), _pp);
// qy = -8*y1^4 + M(S-T)
uint256 qy = addmod(mulmod(m, addmod(s, _pp - qx, _pp), _pp), _pp - mulmod(8, mulmod(square[1], square[1], _pp), _pp), _pp);
// qz = 2*y1*z1
uint256 qz = mulmod(2, mulmod(_y, _z, _pp), _pp);
return (qx, qy, qz);
}
/// @dev Multiply point (x, y, z) times d.
/// @param _d scalar to multiply
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _z coordinate z of P1
/// @param _aa constant of curve
/// @param _pp the modulus
/// @return (qx, qy, qz) d*P1 in Jacobian
function jacMul(
uint256 _d,
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _aa,
uint256 _pp)
internal pure returns (uint256, uint256, uint256)
{
uint256 remaining = _d;
uint256[3] memory point;
point[0] = _x;
point[1] = _y;
point[2] = _z;
uint256 qx = 0;
uint256 qy = 0;
uint256 qz = 1;
if (_d == 0) {
return (qx, qy, qz);
}
// Double and add algorithm
while (remaining != 0) {
if ((remaining & 1) != 0) {
(qx, qy, qz) = jacAdd(
qx,
qy,
qz,
point[0],
point[1],
point[2],
_pp);
}
remaining = remaining / 2;
(point[0], point[1], point[2]) = jacDouble(
point[0],
point[1],
point[2],
_aa,
_pp);
}
return (qx, qy, qz);
}
}
// File: vrf-solidity/contracts/VRF.sol
/**
* @title Verifiable Random Functions (VRF)
* @notice Library verifying VRF proofs using the `Secp256k1` curve and the `SHA256` hash function.
* @dev This library follows the algorithms described in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04) and [RFC6979](https://tools.ietf.org/html/rfc6979).
* It supports the _SECP256K1_SHA256_TAI_ cipher suite, i.e. the aforementioned algorithms using `SHA256` and the `Secp256k1` curve.
* @author Witnet Foundation
*/
library VRF {
/**
* Secp256k1 parameters
*/
// Generator coordinate `x` of the EC curve
uint256 public constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
// Generator coordinate `y` of the EC curve
uint256 public constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
// Constant `a` of EC equation
uint256 public constant AA = 0;
// Constant `b` of EC equation
uint256 public constant BB = 7;
// Prime number of the curve
uint256 public constant PP = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
// Order of the curve
uint256 public constant NN = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
/// @dev Public key derivation from private key.
/// @param _d The scalar
/// @param _x The coordinate x
/// @param _y The coordinate y
/// @return (qx, qy) The derived point
function derivePoint(uint256 _d, uint256 _x, uint256 _y) internal pure returns (uint256, uint256) {
return EllipticCurve.ecMul(
_d,
_x,
_y,
AA,
PP
);
}
/// @dev Function to derive the `y` coordinate given the `x` coordinate and the parity byte (`0x03` for odd `y` and `0x04` for even `y`).
/// @param _yByte The parity byte following the ec point compressed format
/// @param _x The coordinate `x` of the point
/// @return The coordinate `y` of the point
function deriveY(uint8 _yByte, uint256 _x) internal pure returns (uint256) {
return EllipticCurve.deriveY(
_yByte,
_x,
AA,
BB,
PP);
}
/// @dev Computes the VRF hash output as result of the digest of a ciphersuite-dependent prefix
/// concatenated with the gamma point
/// @param _gammaX The x-coordinate of the gamma EC point
/// @param _gammaY The y-coordinate of the gamma EC point
/// @return The VRF hash ouput as shas256 digest
function gammaToHash(uint256 _gammaX, uint256 _gammaY) internal pure returns (bytes32) {
bytes memory c = abi.encodePacked(
// Cipher suite code (SECP256K1-SHA256-TAI is 0xFE)
uint8(0xFE),
// 0x01
uint8(0x03),
// Compressed Gamma Point
encodePoint(_gammaX, _gammaY));
return sha256(c);
}
/// @dev VRF verification by providing the public key, the message and the VRF proof.
/// This function computes several elliptic curve operations which may lead to extensive gas consumption.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @param _message The message (in bytes) used for computing the VRF
/// @return true, if VRF proof is valid
function verify(uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message) internal pure returns (bool) {
// Step 2: Hash to try and increment (outputs a hashed value, a finite EC point in G)
uint256[2] memory hPoint;
(hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message);
// Step 3: U = s*B - c*Y (where B is the generator)
(uint256 uPointX, uint256 uPointY) = ecMulSubMul(
_proof[3],
GX,
GY,
_proof[2],
_publicKey[0],
_publicKey[1]);
// Step 4: V = s*H - c*Gamma
(uint256 vPointX, uint256 vPointY) = ecMulSubMul(
_proof[3],
hPoint[0],
hPoint[1],
_proof[2],
_proof[0],_proof[1]);
// Step 5: derived c from hash points(...)
bytes16 derivedC = hashPoints(
hPoint[0],
hPoint[1],
_proof[0],
_proof[1],
uPointX,
uPointY,
vPointX,
vPointY);
// Step 6: Check validity c == c'
return uint128(derivedC) == _proof[2];
}
/// @dev VRF fast verification by providing the public key, the message, the VRF proof and several intermediate elliptic curve points that enable the verification shortcut.
/// This function leverages the EVM's `ecrecover` precompile to verify elliptic curve multiplications by decreasing the security from 32 to 20 bytes.
/// Based on the original idea of Vitalik Buterin: https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @param _message The message (in bytes) used for computing the VRF
/// @param _uPoint The `u` EC point defined as `U = s*B - c*Y`
/// @param _vComponents The components required to compute `v` as `V = s*H - c*Gamma`
/// @return true, if VRF proof is valid
function fastVerify(
uint256[2] memory _publicKey,
uint256[4] memory _proof,
bytes memory _message,
uint256[2] memory _uPoint,
uint256[4] memory _vComponents)
internal pure returns (bool)
{
// Step 2: Hash to try and increment -> hashed value, a finite EC point in G
uint256[2] memory hPoint;
(hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message);
// Step 3 & Step 4:
// U = s*B - c*Y (where B is the generator)
// V = s*H - c*Gamma
if (!ecMulSubMulVerify(
_proof[3],
_proof[2],
_publicKey[0],
_publicKey[1],
_uPoint[0],
_uPoint[1]) ||
!ecMulVerify(
_proof[3],
hPoint[0],
hPoint[1],
_vComponents[0],
_vComponents[1]) ||
!ecMulVerify(
_proof[2],
_proof[0],
_proof[1],
_vComponents[2],
_vComponents[3])
)
{
return false;
}
(uint256 vPointX, uint256 vPointY) = EllipticCurve.ecSub(
_vComponents[0],
_vComponents[1],
_vComponents[2],
_vComponents[3],
AA,
PP);
// Step 5: derived c from hash points(...)
bytes16 derivedC = hashPoints(
hPoint[0],
hPoint[1],
_proof[0],
_proof[1],
_uPoint[0],
_uPoint[1],
vPointX,
vPointY);
// Step 6: Check validity c == c'
return uint128(derivedC) == _proof[2];
}
/// @dev Decode VRF proof from bytes
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @return The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
function decodeProof(bytes memory _proof) internal pure returns (uint[4] memory) {
require(_proof.length == 81, "Malformed VRF proof");
uint8 gammaSign;
uint256 gammaX;
uint128 c;
uint256 s;
assembly {
gammaSign := mload(add(_proof, 1))
gammaX := mload(add(_proof, 33))
c := mload(add(_proof, 49))
s := mload(add(_proof, 81))
}
uint256 gammaY = deriveY(gammaSign, gammaX);
return [
gammaX,
gammaY,
c,
s];
}
/// @dev Decode EC point from bytes
/// @param _point The EC point as bytes
/// @return The point as `[point-x, point-y]`
function decodePoint(bytes memory _point) internal pure returns (uint[2] memory) {
require(_point.length == 33, "Malformed compressed EC point");
uint8 sign;
uint256 x;
assembly {
sign := mload(add(_point, 1))
x := mload(add(_point, 33))
}
uint256 y = deriveY(sign, x);
return [x, y];
}
/// @dev Compute the parameters (EC points) required for the VRF fast verification function.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @param _message The message (in bytes) used for computing the VRF
/// @return The fast verify required parameters as the tuple `([uPointX, uPointY], [sHX, sHY, cGammaX, cGammaY])`
function computeFastVerifyParams(uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message)
internal pure returns (uint256[2] memory, uint256[4] memory)
{
// Requirements for Step 3: U = s*B - c*Y (where B is the generator)
uint256[2] memory hPoint;
(hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message);
(uint256 uPointX, uint256 uPointY) = ecMulSubMul(
_proof[3],
GX,
GY,
_proof[2],
_publicKey[0],
_publicKey[1]);
// Requirements for Step 4: V = s*H - c*Gamma
(uint256 sHX, uint256 sHY) = derivePoint(_proof[3], hPoint[0], hPoint[1]);
(uint256 cGammaX, uint256 cGammaY) = derivePoint(_proof[2], _proof[0], _proof[1]);
return (
[uPointX, uPointY],
[
sHX,
sHY,
cGammaX,
cGammaY
]);
}
/// @dev Function to convert a `Hash(PK|DATA)` to a point in the curve as defined in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04).
/// Used in Step 2 of VRF verification function.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _message The message used for computing the VRF
/// @return The hash point in affine cooridnates
function hashToTryAndIncrement(uint256[2] memory _publicKey, bytes memory _message) internal pure returns (uint, uint) {
// Step 1: public key to bytes
// Step 2: V = cipher_suite | 0x01 | public_key_bytes | message | ctr
bytes memory c = abi.encodePacked(
// Cipher suite code (SECP256K1-SHA256-TAI is 0xFE)
uint8(254),
// 0x01
uint8(1),
// Public Key
encodePoint(_publicKey[0], _publicKey[1]),
// Message
_message);
// Step 3: find a valid EC point
// Loop over counter ctr starting at 0x00 and do hash
for (uint8 ctr = 0; ctr < 256; ctr++) {
// Counter update
// c[cLength-1] = byte(ctr);
bytes32 sha = sha256(abi.encodePacked(c, ctr));
// Step 4: arbitraty string to point and check if it is on curve
uint hPointX = uint256(sha);
uint hPointY = deriveY(2, hPointX);
if (EllipticCurve.isOnCurve(
hPointX,
hPointY,
AA,
BB,
PP))
{
// Step 5 (omitted): calculate H (cofactor is 1 on secp256k1)
// If H is not "INVALID" and cofactor > 1, set H = cofactor * H
return (hPointX, hPointY);
}
}
revert("No valid point was found");
}
/// @dev Function to hash a certain set of points as specified in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04).
/// Used in Step 5 of VRF verification function.
/// @param _hPointX The coordinate `x` of point `H`
/// @param _hPointY The coordinate `y` of point `H`
/// @param _gammaX The coordinate `x` of the point `Gamma`
/// @param _gammaX The coordinate `y` of the point `Gamma`
/// @param _uPointX The coordinate `x` of point `U`
/// @param _uPointY The coordinate `y` of point `U`
/// @param _vPointX The coordinate `x` of point `V`
/// @param _vPointY The coordinate `y` of point `V`
/// @return The first half of the digest of the points using SHA256
function hashPoints(
uint256 _hPointX,
uint256 _hPointY,
uint256 _gammaX,
uint256 _gammaY,
uint256 _uPointX,
uint256 _uPointY,
uint256 _vPointX,
uint256 _vPointY)
internal pure returns (bytes16)
{
bytes memory c = abi.encodePacked(
// Ciphersuite 0xFE
uint8(254),
// Prefix 0x02
uint8(2),
// Points to Bytes
encodePoint(_hPointX, _hPointY),
encodePoint(_gammaX, _gammaY),
encodePoint(_uPointX, _uPointY),
encodePoint(_vPointX, _vPointY)
);
// Hash bytes and truncate
bytes32 sha = sha256(c);
bytes16 half1;
assembly {
let freemem_pointer := mload(0x40)
mstore(add(freemem_pointer,0x00), sha)
half1 := mload(add(freemem_pointer,0x00))
}
return half1;
}
/// @dev Encode an EC point to bytes
/// @param _x The coordinate `x` of the point
/// @param _y The coordinate `y` of the point
/// @return The point coordinates as bytes
function encodePoint(uint256 _x, uint256 _y) internal pure returns (bytes memory) {
uint8 prefix = uint8(2 + (_y % 2));
return abi.encodePacked(prefix, _x);
}
/// @dev Substracts two key derivation functionsas `s1*A - s2*B`.
/// @param _scalar1 The scalar `s1`
/// @param _a1 The `x` coordinate of point `A`
/// @param _a2 The `y` coordinate of point `A`
/// @param _scalar2 The scalar `s2`
/// @param _b1 The `x` coordinate of point `B`
/// @param _b2 The `y` coordinate of point `B`
/// @return The derived point in affine cooridnates
function ecMulSubMul(
uint256 _scalar1,
uint256 _a1,
uint256 _a2,
uint256 _scalar2,
uint256 _b1,
uint256 _b2)
internal pure returns (uint256, uint256)
{
(uint256 m1, uint256 m2) = derivePoint(_scalar1, _a1, _a2);
(uint256 n1, uint256 n2) = derivePoint(_scalar2, _b1, _b2);
(uint256 r1, uint256 r2) = EllipticCurve.ecSub(
m1,
m2,
n1,
n2,
AA,
PP);
return (r1, r2);
}
/// @dev Verify an Elliptic Curve multiplication of the form `(qx,qy) = scalar*(x,y)` by using the precompiled `ecrecover` function.
/// The usage of the precompiled `ecrecover` function decreases the security from 32 to 20 bytes.
/// Based on the original idea of Vitalik Buterin: https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9
/// @param _scalar The scalar of the point multiplication
/// @param _x The coordinate `x` of the point
/// @param _y The coordinate `y` of the point
/// @param _qx The coordinate `x` of the multiplication result
/// @param _qy The coordinate `y` of the multiplication result
/// @return true, if first 20 bytes match
function ecMulVerify(
uint256 _scalar,
uint256 _x,
uint256 _y,
uint256 _qx,
uint256 _qy)
internal pure returns(bool)
{
address result = ecrecover(
0,
_y % 2 != 0 ? 28 : 27,
bytes32(_x),
bytes32(mulmod(_scalar, _x, NN)));
return pointToAddress(_qx, _qy) == result;
}
/// @dev Verify an Elliptic Curve operation of the form `Q = scalar1*(gx,gy) - scalar2*(x,y)` by using the precompiled `ecrecover` function, where `(gx,gy)` is the generator of the EC.
/// The usage of the precompiled `ecrecover` function decreases the security from 32 to 20 bytes.
/// Based on SolCrypto library: https://github.com/HarryR/solcrypto
/// @param _scalar1 The scalar of the multiplication of `(gx,gy)`
/// @param _scalar2 The scalar of the multiplication of `(x,y)`
/// @param _x The coordinate `x` of the point to be mutiply by `scalar2`
/// @param _y The coordinate `y` of the point to be mutiply by `scalar2`
/// @param _qx The coordinate `x` of the equation result
/// @param _qy The coordinate `y` of the equation result
/// @return true, if first 20 bytes match
function ecMulSubMulVerify(
uint256 _scalar1,
uint256 _scalar2,
uint256 _x,
uint256 _y,
uint256 _qx,
uint256 _qy)
internal pure returns(bool)
{
uint256 scalar1 = (NN - _scalar1) % NN;
scalar1 = mulmod(scalar1, _x, NN);
uint256 scalar2 = (NN - _scalar2) % NN;
address result = ecrecover(
bytes32(scalar1),
_y % 2 != 0 ? 28 : 27,
bytes32(_x),
bytes32(mulmod(scalar2, _x, NN)));
return pointToAddress(_qx, _qy) == result;
}
/// @dev Gets the address corresponding to the EC point digest (keccak256), i.e. the first 20 bytes of the digest.
/// This function is used for performing a fast EC multiplication verification.
/// @param _x The coordinate `x` of the point
/// @param _y The coordinate `y` of the point
/// @return The address of the EC point digest (keccak256)
function pointToAddress(uint256 _x, uint256 _y)
internal pure returns(address)
{
return address(uint256(keccak256(abi.encodePacked(_x, _y))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
}
}
// File: witnet-ethereum-bridge/contracts/ActiveBridgeSetLib.sol
/**
* @title Active Bridge Set (ABS) library
* @notice This library counts the number of bridges that were active recently.
*/
library ActiveBridgeSetLib {
// Number of Ethereum blocks during which identities can be pushed into a single activity slot
uint8 public constant CLAIM_BLOCK_PERIOD = 8;
// Number of activity slots in the ABS
uint8 public constant ACTIVITY_LENGTH = 100;
struct ActiveBridgeSet {
// Mapping of activity slots with participating identities
mapping (uint16 => address[]) epochIdentities;
// Mapping of identities with their participation count
mapping (address => uint16) identityCount;
// Number of identities in the Active Bridge Set (consolidated during `ACTIVITY_LENGTH`)
uint32 activeIdentities;
// Number of identities for the next activity slot (to be updated in the next activity slot)
uint32 nextActiveIdentities;
// Last used block number during an activity update
uint256 lastBlockNumber;
}
modifier validBlockNumber(uint256 _blockFromArguments, uint256 _blockFromContractState) {
require (_blockFromArguments >= _blockFromContractState, "The provided block is older than the last updated block");
_;
}
/// @dev Updates activity in Witnet without requiring protocol participation.
/// @param _abs The Active Bridge Set structure to be updated.
/// @param _blockNumber The block number up to which the activity should be updated.
function updateActivity(ActiveBridgeSet storage _abs, uint256 _blockNumber)
internal
validBlockNumber(_blockNumber, _abs.lastBlockNumber)
{
(uint16 currentSlot, uint16 lastSlot, bool overflow) = getSlots(_abs, _blockNumber);
// Avoid gas cost if ABS is up to date
require(
updateABS(
_abs,
currentSlot,
lastSlot,
overflow
), "The ABS was already up to date");
_abs.lastBlockNumber = _blockNumber;
}
/// @dev Pushes activity updates through protocol activities (implying insertion of identity).
/// @param _abs The Active Bridge Set structure to be updated.
/// @param _address The address pushing the activity.
/// @param _blockNumber The block number up to which the activity should be updated.
function pushActivity(ActiveBridgeSet storage _abs, address _address, uint256 _blockNumber)
internal
validBlockNumber(_blockNumber, _abs.lastBlockNumber)
returns (bool success)
{
(uint16 currentSlot, uint16 lastSlot, bool overflow) = getSlots(_abs, _blockNumber);
// Update ABS and if it was already up to date, check if identities already counted
if (
updateABS(
_abs,
currentSlot,
lastSlot,
overflow
))
{
_abs.lastBlockNumber = _blockNumber;
} else {
// Check if address was already counted as active identity in this current activity slot
uint256 epochIdsLength = _abs.epochIdentities[currentSlot].length;
for (uint256 i; i < epochIdsLength; i++) {
if (_abs.epochIdentities[currentSlot][i] == _address) {
return false;
}
}
}
// Update current activity slot with identity:
// 1. Add currentSlot to `epochIdentities` with address
// 2. If count = 0, increment by 1 `nextActiveIdentities`
// 3. Increment by 1 the count of the identity
_abs.epochIdentities[currentSlot].push(_address);
if (_abs.identityCount[_address] == 0) {
_abs.nextActiveIdentities++;
}
_abs.identityCount[_address]++;
return true;
}
/// @dev Checks if an address is a member of the ABS.
/// @param _abs The Active Bridge Set structure from the Witnet Requests Board.
/// @param _address The address to check.
/// @return true if address is member of ABS.
function absMembership(ActiveBridgeSet storage _abs, address _address) internal view returns (bool) {
return _abs.identityCount[_address] > 0;
}
/// @dev Gets the slots of the last block seen by the ABS provided and the block number provided.
/// @param _abs The Active Bridge Set structure containing the last block.
/// @param _blockNumber The block number from which to get the current slot.
/// @return (currentSlot, lastSlot, overflow), where overflow implies the block difference > CLAIM_BLOCK_PERIOD* ACTIVITY_LENGTH.
function getSlots(ActiveBridgeSet storage _abs, uint256 _blockNumber) private view returns (uint8, uint8, bool) {
// Get current activity slot number
uint8 currentSlot = uint8((_blockNumber / CLAIM_BLOCK_PERIOD) % ACTIVITY_LENGTH);
// Get last actitivy slot number
uint8 lastSlot = uint8((_abs.lastBlockNumber / CLAIM_BLOCK_PERIOD) % ACTIVITY_LENGTH);
// Check if there was an activity slot overflow
// `ACTIVITY_LENGTH` is changed to `uint16` here to ensure the multiplication doesn't overflow silently
bool overflow = (_blockNumber - _abs.lastBlockNumber) >= CLAIM_BLOCK_PERIOD * uint16(ACTIVITY_LENGTH);
return (currentSlot, lastSlot, overflow);
}
/// @dev Updates the provided ABS according to the slots provided.
/// @param _abs The Active Bridge Set to be updated.
/// @param _currentSlot The current slot.
/// @param _lastSlot The last slot seen by the ABS.
/// @param _overflow Whether the current slot has overflown the last slot.
/// @return True if update occurred.
function updateABS(
ActiveBridgeSet storage _abs,
uint16 _currentSlot,
uint16 _lastSlot,
bool _overflow)
private
returns (bool)
{
// If there are more than `ACTIVITY_LENGTH` slots empty => remove entirely the ABS
if (_overflow) {
flushABS(_abs, _lastSlot, _lastSlot);
// If ABS are not up to date => fill previous activity slots with empty activities
} else if (_currentSlot != _lastSlot) {
flushABS(_abs, _currentSlot, _lastSlot);
} else {
return false;
}
return true;
}
/// @dev Flushes the provided ABS record between lastSlot and currentSlot.
/// @param _abs The Active Bridge Set to be flushed.
/// @param _currentSlot The current slot.
function flushABS(ActiveBridgeSet storage _abs, uint16 _currentSlot, uint16 _lastSlot) private {
// For each slot elapsed, remove identities and update `nextActiveIdentities` count
for (uint16 slot = (_lastSlot + 1) % ACTIVITY_LENGTH ; slot != _currentSlot ; slot = (slot + 1) % ACTIVITY_LENGTH) {
flushSlot(_abs, slot);
}
// Update current activity slot
flushSlot(_abs, _currentSlot);
_abs.activeIdentities = _abs.nextActiveIdentities;
}
/// @dev Flushes a slot of the provided ABS.
/// @param _abs The Active Bridge Set to be flushed.
/// @param _slot The slot to be flushed.
function flushSlot(ActiveBridgeSet storage _abs, uint16 _slot) private {
// For a given slot, go through all identities to flush them
uint256 epochIdsLength = _abs.epochIdentities[_slot].length;
for (uint256 id = 0; id < epochIdsLength; id++) {
flushIdentity(_abs, _abs.epochIdentities[_slot][id]);
}
delete _abs.epochIdentities[_slot];
}
/// @dev Decrements the appearance counter of an identity from the provided ABS. If the counter reaches 0, the identity is flushed.
/// @param _abs The Active Bridge Set to be flushed.
/// @param _address The address to be flushed.
function flushIdentity(ActiveBridgeSet storage _abs, address _address) private {
require(absMembership(_abs, _address), "The identity address is already out of the ARS");
// Decrement the count of an identity, and if it reaches 0, delete it and update `nextActiveIdentities`count
_abs.identityCount[_address]--;
if (_abs.identityCount[_address] == 0) {
delete _abs.identityCount[_address];
_abs.nextActiveIdentities--;
}
}
}
// File: witnet-ethereum-bridge/contracts/WitnetRequestsBoardInterface.sol
/**
* @title Witnet Requests Board Interface
* @notice Interface of a Witnet Request Board (WRB)
* It defines how to interact with the WRB in order to support:
* - Post and upgrade a data request
* - Read the result of a dr
* @author Witnet Foundation
*/
interface WitnetRequestsBoardInterface {
/// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value.
/// @param _dr The bytes corresponding to the Protocol Buffers serialization of the data request output.
/// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request.
/// @return The unique identifier of the data request.
function postDataRequest(bytes calldata _dr, uint256 _tallyReward) external payable returns(uint256);
/// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward.
/// @param _id The unique identifier of the data request.
/// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward.
function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable;
/// @dev Retrieves the DR hash of the id from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The hash of the DR
function readDrHash (uint256 _id) external view returns(uint256);
/// @dev Retrieves the result (if already available) of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the DR
function readResult (uint256 _id) external view returns(bytes memory);
/// @notice Verifies if the block relay can be upgraded.
/// @return true if contract is upgradable.
function isUpgradable(address _address) external view returns(bool);
}
// File: witnet-ethereum-bridge/contracts/WitnetRequestsBoard.sol
/**
* @title Witnet Requests Board
* @notice Contract to bridge requests to Witnet.
* @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network.
* The result of the requests will be posted back to this contract by the bridge nodes too.
* @author Witnet Foundation
*/
contract WitnetRequestsBoard is WitnetRequestsBoardInterface {
using ActiveBridgeSetLib for ActiveBridgeSetLib.ActiveBridgeSet;
// Expiration period after which a Witnet Request can be claimed again
uint256 public constant CLAIM_EXPIRATION = 13;
struct DataRequest {
bytes dr;
uint256 inclusionReward;
uint256 tallyReward;
bytes result;
// Block number at which the DR was claimed for the last time
uint256 blockNumber;
uint256 drHash;
address payable pkhClaim;
}
// Owner of the Witnet Request Board
address public witnet;
// Block Relay proxy prividing verification functions
BlockRelayProxy public blockRelay;
// Witnet Requests within the board
DataRequest[] public requests;
// Set of recently active bridges
ActiveBridgeSetLib.ActiveBridgeSet public abs;
// Replication factor for Active Bridge Set identities
uint8 public repFactor;
// Event emitted when a new DR is posted
event PostedRequest(address indexed _from, uint256 _id);
// Event emitted when a DR inclusion proof is posted
event IncludedRequest(address indexed _from, uint256 _id);
// Event emitted when a result proof is posted
event PostedResult(address indexed _from, uint256 _id);
// Ensures the reward is not greater than the value
modifier payingEnough(uint256 _value, uint256 _tally) {
require(_value >= _tally, "Transaction value needs to be equal or greater than tally reward");
_;
}
// Ensures the poe is valid
modifier poeValid(
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers) {
require(
verifyPoe(
_poe,
_publicKey,
_uPoint,
_vPointHelpers),
"Not a valid PoE");
_;
}
// Ensures signature (sign(msg.sender)) is valid
modifier validSignature(
uint256[2] memory _publicKey,
bytes memory addrSignature) {
require(verifySig(abi.encodePacked(msg.sender), _publicKey, addrSignature), "Not a valid signature");
_;
}
// Ensures the DR inclusion proof has not been reported yet
modifier drNotIncluded(uint256 _id) {
require(requests[_id].drHash == 0, "DR already included");
_;
}
// Ensures the DR inclusion has been already reported
modifier drIncluded(uint256 _id) {
require(requests[_id].drHash != 0, "DR not yet included");
_;
}
// Ensures the result has not been reported yet
modifier resultNotIncluded(uint256 _id) {
require(requests[_id].result.length == 0, "Result already included");
_;
}
// Ensures the VRF is valid
modifier vrfValid(
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers) virtual {
require(
VRF.fastVerify(
_publicKey,
_poe,
getLastBeacon(),
_uPoint,
_vPointHelpers),
"Not a valid VRF");
_;
}
// Ensures the address belongs to the active bridge set
modifier absMember(address _address) {
require(abs.absMembership(_address), "Not a member of the ABS");
_;
}
/**
* @notice Include an address to specify the Witnet Block Relay and a replication factor.
* @param _blockRelayAddress BlockRelayProxy address.
* @param _repFactor replication factor.
*/
constructor(address _blockRelayAddress, uint8 _repFactor) public {
blockRelay = BlockRelayProxy(_blockRelayAddress);
witnet = msg.sender;
// Insert an empty request so as to initialize the requests array with length > 0
DataRequest memory request;
requests.push(request);
repFactor = _repFactor;
}
/// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value.
/// @param _serialized The bytes corresponding to the Protocol Buffers serialization of the data request output.
/// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request.
/// @return The unique identifier of the data request.
function postDataRequest(bytes calldata _serialized, uint256 _tallyReward)
external
payable
payingEnough(msg.value, _tallyReward)
override
returns(uint256)
{
// The initial length of the `requests` array will become the ID of the request for everything related to the WRB
uint256 id = requests.length;
// Create a new `DataRequest` object and initialize all the non-default fields
DataRequest memory request;
request.dr = _serialized;
request.inclusionReward = SafeMath.sub(msg.value, _tallyReward);
request.tallyReward = _tallyReward;
// Push the new request into the contract state
requests.push(request);
// Let observers know that a new request has been posted
emit PostedRequest(msg.sender, id);
return id;
}
/// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward.
/// @param _id The unique identifier of the data request.
/// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward.
function upgradeDataRequest(uint256 _id, uint256 _tallyReward)
external
payable
payingEnough(msg.value, _tallyReward)
resultNotIncluded(_id)
override
{
if (requests[_id].drHash != 0) {
require(
msg.value == _tallyReward,
"Txn value should equal result reward argument (request reward already paid)"
);
requests[_id].tallyReward = SafeMath.add(requests[_id].tallyReward, _tallyReward);
} else {
requests[_id].inclusionReward = SafeMath.add(requests[_id].inclusionReward, msg.value - _tallyReward);
requests[_id].tallyReward = SafeMath.add(requests[_id].tallyReward, _tallyReward);
}
}
/// @dev Checks if the data requests from a list are claimable or not.
/// @param _ids The list of data request identifiers to be checked.
/// @return An array of booleans indicating if data requests are claimable or not.
function checkDataRequestsClaimability(uint256[] calldata _ids) external view returns (bool[] memory) {
uint256 idsLength = _ids.length;
bool[] memory validIds = new bool[](idsLength);
for (uint i = 0; i < idsLength; i++) {
uint256 index = _ids[i];
validIds[i] = (dataRequestCanBeClaimed(requests[index])) &&
requests[index].drHash == 0 &&
index < requests.length &&
requests[index].result.length == 0;
}
return validIds;
}
/// @dev Presents a proof of inclusion to prove that the request was posted into Witnet so as to unlock the inclusion reward that was put aside for the claiming identity (public key hash).
/// @param _id The unique identifier of the data request.
/// @param _poi A proof of inclusion proving that the data request appears listed in one recent block in Witnet.
/// @param _index The index in the merkle tree.
/// @param _blockHash The hash of the block in which the data request was inserted.
/// @param _epoch The epoch in which the blockHash was created.
function reportDataRequestInclusion(
uint256 _id,
uint256[] calldata _poi,
uint256 _index,
uint256 _blockHash,
uint256 _epoch)
external
drNotIncluded(_id)
{
// Check the data request has been claimed
require(dataRequestCanBeClaimed(requests[_id]) == false, "Data Request has not yet been claimed");
uint256 drOutputHash = uint256(sha256(requests[_id].dr));
uint256 drHash = uint256(sha256(abi.encodePacked(drOutputHash, _poi[0])));
// Update the state upon which this function depends before the external call
requests[_id].drHash = drHash;
require(
blockRelay.verifyDrPoi(
_poi,
_blockHash,
_epoch,
_index,
drOutputHash), "Invalid PoI");
requests[_id].pkhClaim.transfer(requests[_id].inclusionReward);
// Push requests[_id].pkhClaim to abs
abs.pushActivity(requests[_id].pkhClaim, block.number);
emit IncludedRequest(msg.sender, _id);
}
/// @dev Reports the result of a data request in Witnet.
/// @param _id The unique identifier of the data request.
/// @param _poi A proof of inclusion proving that the data in _result has been acknowledged by the Witnet network as being the final result for the data request by putting in a tally transaction inside a Witnet block.
/// @param _index The position of the tally transaction in the tallies-only merkle tree in the Witnet block.
/// @param _blockHash The hash of the block in which the result (tally) was inserted.
/// @param _epoch The epoch in which the blockHash was created.
/// @param _result The result itself as bytes.
function reportResult(
uint256 _id,
uint256[] calldata _poi,
uint256 _index,
uint256 _blockHash,
uint256 _epoch,
bytes calldata _result)
external
drIncluded(_id)
resultNotIncluded(_id)
absMember(msg.sender)
{
// Ensures the result byes do not have zero length
// This would not be a valid encoding with CBOR and could trigger a reentrancy attack
require(_result.length != 0, "Result has zero length");
// Update the state upon which this function depends before the external call
requests[_id].result = _result;
uint256 resHash = uint256(sha256(abi.encodePacked(requests[_id].drHash, _result)));
require(
blockRelay.verifyTallyPoi(
_poi,
_blockHash,
_epoch,
_index,
resHash), "Invalid PoI");
msg.sender.transfer(requests[_id].tallyReward);
emit PostedResult(msg.sender, _id);
}
/// @dev Retrieves the bytes of the serialization of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the data request as bytes.
function readDataRequest(uint256 _id) external view returns(bytes memory) {
require(requests.length > _id, "Id not found");
return requests[_id].dr;
}
/// @dev Retrieves the result (if already available) of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the DR
function readResult(uint256 _id) external view override returns(bytes memory) {
require(requests.length > _id, "Id not found");
return requests[_id].result;
}
/// @dev Retrieves hash of the data request transaction in Witnet.
/// @param _id The unique identifier of the data request.
/// @return The hash of the DataRequest transaction in Witnet.
function readDrHash(uint256 _id) external view override returns(uint256) {
require(requests.length > _id, "Id not found");
return requests[_id].drHash;
}
/// @dev Returns the number of data requests in the WRB.
/// @return the number of data requests in the WRB.
function requestsCount() external view returns(uint256) {
return requests.length;
}
/// @notice Wrapper around the decodeProof from VRF library.
/// @dev Decode VRF proof from bytes.
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`.
/// @return The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`.
function decodeProof(bytes calldata _proof) external pure returns (uint[4] memory) {
return VRF.decodeProof(_proof);
}
/// @notice Wrapper around the decodePoint from VRF library.
/// @dev Decode EC point from bytes.
/// @param _point The EC point as bytes.
/// @return The point as `[point-x, point-y]`.
function decodePoint(bytes calldata _point) external pure returns (uint[2] memory) {
return VRF.decodePoint(_point);
}
/// @dev Wrapper around the computeFastVerifyParams from VRF library.
/// @dev Compute the parameters (EC points) required for the VRF fast verification function..
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`.
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`.
/// @param _message The message (in bytes) used for computing the VRF.
/// @return The fast verify required parameters as the tuple `([uPointX, uPointY], [sHX, sHY, cGammaX, cGammaY])`.
function computeFastVerifyParams(uint256[2] calldata _publicKey, uint256[4] calldata _proof, bytes calldata _message)
external pure returns (uint256[2] memory, uint256[4] memory)
{
return VRF.computeFastVerifyParams(_publicKey, _proof, _message);
}
/// @dev Updates the ABS activity with the block number provided.
/// @param _blockNumber update the ABS until this block number.
function updateAbsActivity(uint256 _blockNumber) external {
require (_blockNumber <= block.number, "The provided block number has not been reached");
abs.updateActivity(_blockNumber);
}
/// @dev Verifies if the contract is upgradable.
/// @return true if the contract upgradable.
function isUpgradable(address _address) external view override returns(bool) {
if (_address == witnet) {
return true;
}
return false;
}
/// @dev Claim drs to be posted to Witnet by the node.
/// @param _ids Data request ids to be claimed.
/// @param _poe PoE claiming eligibility.
/// @param _uPoint uPoint coordinates as [uPointX, uPointY] corresponding to U = s*B - c*Y.
/// @param _vPointHelpers helpers for calculating the V point as [(s*H)X, (s*H)Y, cGammaX, cGammaY]. V = s*H + cGamma.
function claimDataRequests(
uint256[] memory _ids,
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers,
bytes memory addrSignature)
public
validSignature(_publicKey, addrSignature)
poeValid(_poe,_publicKey, _uPoint,_vPointHelpers)
returns(bool)
{
for (uint i = 0; i < _ids.length; i++) {
require(
dataRequestCanBeClaimed(requests[_ids[i]]),
"One of the listed data requests was already claimed"
);
requests[_ids[i]].pkhClaim = msg.sender;
requests[_ids[i]].blockNumber = block.number;
}
return true;
}
/// @dev Read the beacon of the last block inserted.
/// @return bytes to be signed by the node as PoE.
function getLastBeacon() public view virtual returns(bytes memory) {
return blockRelay.getLastBeacon();
}
/// @dev Claim drs to be posted to Witnet by the node.
/// @param _poe PoE claiming eligibility.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`.
/// @param _uPoint uPoint coordinates as [uPointX, uPointY] corresponding to U = s*B - c*Y.
/// @param _vPointHelpers helpers for calculating the V point as [(s*H)X, (s*H)Y, cGammaX, cGammaY]. V = s*H + cGamma.
function verifyPoe(
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers)
internal
view
vrfValid(_poe,_publicKey, _uPoint,_vPointHelpers)
returns(bool)
{
uint256 vrf = uint256(VRF.gammaToHash(_poe[0], _poe[1]));
// True if vrf/(2^{256} -1) <= repFactor/abs.activeIdentities
if (abs.activeIdentities < repFactor) {
return true;
}
// We rewrote it as vrf <= ((2^{256} -1)/abs.activeIdentities)*repFactor to gain efficiency
if (vrf <= ((~uint256(0)/abs.activeIdentities)*repFactor)) {
return true;
}
return false;
}
/// @dev Verifies the validity of a signature.
/// @param _message message to be verified.
/// @param _publicKey public key of the signer as `[pubKey-x, pubKey-y]`.
/// @param _addrSignature the signature to verify asas r||s||v.
/// @return true or false depending the validity.
function verifySig(
bytes memory _message,
uint256[2] memory _publicKey,
bytes memory _addrSignature)
internal
pure
returns(bool)
{
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(_addrSignature, 0x20))
s := mload(add(_addrSignature, 0x40))
v := byte(0, mload(add(_addrSignature, 0x60)))
}
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return false;
}
if (v != 0 && v != 1) {
return false;
}
v = 28 - v;
bytes32 msgHash = sha256(_message);
address hashedKey = VRF.pointToAddress(_publicKey[0], _publicKey[1]);
return ecrecover(
msgHash,
v,
r,
s) == hashedKey;
}
function dataRequestCanBeClaimed(DataRequest memory _request) private view returns (bool) {
return
(_request.blockNumber == 0 || block.number - _request.blockNumber > CLAIM_EXPIRATION) &&
_request.drHash == 0 &&
_request.result.length == 0;
}
}
// File: witnet-ethereum-bridge/contracts/WitnetRequestsBoardProxy.sol
/**
* @title Block Relay Proxy
* @notice Contract to act as a proxy between the Witnet Bridge Interface and the Block Relay.
* @author Witnet Foundation
*/
contract WitnetRequestsBoardProxy {
// Address of the Witnet Request Board contract that is currently being used
address public witnetRequestsBoardAddress;
// Struct if the information of each controller
struct ControllerInfo {
// Address of the Controller
address controllerAddress;
// The lastId of the previous Controller
uint256 lastId;
}
// Last id of the WRB controller
uint256 internal currentLastId;
// Instance of the current WitnetRequestBoard
WitnetRequestsBoardInterface internal witnetRequestsBoardInstance;
// Array with the controllers that have been used in the Proxy
ControllerInfo[] internal controllers;
modifier notIdentical(address _newAddress) {
require(_newAddress != witnetRequestsBoardAddress, "The provided Witnet Requests Board instance address is already in use");
_;
}
/**
* @notice Include an address to specify the Witnet Request Board.
* @param _witnetRequestsBoardAddress WitnetRequestBoard address.
*/
constructor(address _witnetRequestsBoardAddress) public {
// Initialize the first epoch pointing to the first controller
controllers.push(ControllerInfo({controllerAddress: _witnetRequestsBoardAddress, lastId: 0}));
witnetRequestsBoardAddress = _witnetRequestsBoardAddress;
witnetRequestsBoardInstance = WitnetRequestsBoardInterface(_witnetRequestsBoardAddress);
}
/// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value.
/// @param _dr The bytes corresponding to the Protocol Buffers serialization of the data request output.
/// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request.
/// @return The unique identifier of the data request.
function postDataRequest(bytes calldata _dr, uint256 _tallyReward) external payable returns(uint256) {
uint256 n = controllers.length;
uint256 offset = controllers[n - 1].lastId;
// Update the currentLastId with the id in the controller plus the offSet
currentLastId = witnetRequestsBoardInstance.postDataRequest{value: msg.value}(_dr, _tallyReward) + offset;
return currentLastId;
}
/// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward.
/// @param _id The unique identifier of the data request.
/// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward.
function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable {
address wrbAddress;
uint256 wrbOffset;
(wrbAddress, wrbOffset) = getController(_id);
return witnetRequestsBoardInstance.upgradeDataRequest{value: msg.value}(_id - wrbOffset, _tallyReward);
}
/// @dev Retrieves the DR hash of the id from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The hash of the DR.
function readDrHash (uint256 _id)
external
view
returns(uint256)
{
// Get the address and the offset of the corresponding to id
address wrbAddress;
uint256 offsetWrb;
(wrbAddress, offsetWrb) = getController(_id);
// Return the result of the DR readed in the corresponding Controller with its own id
WitnetRequestsBoardInterface wrbWithDrHash;
wrbWithDrHash = WitnetRequestsBoardInterface(wrbAddress);
uint256 drHash = wrbWithDrHash.readDrHash(_id - offsetWrb);
return drHash;
}
/// @dev Retrieves the result (if already available) of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the DR.
function readResult(uint256 _id) external view returns(bytes memory) {
// Get the address and the offset of the corresponding to id
address wrbAddress;
uint256 offSetWrb;
(wrbAddress, offSetWrb) = getController(_id);
// Return the result of the DR in the corresponding Controller with its own id
WitnetRequestsBoardInterface wrbWithResult;
wrbWithResult = WitnetRequestsBoardInterface(wrbAddress);
return wrbWithResult.readResult(_id - offSetWrb);
}
/// @notice Upgrades the Witnet Requests Board if the current one is upgradeable.
/// @param _newAddress address of the new block relay to upgrade.
function upgradeWitnetRequestsBoard(address _newAddress) public notIdentical(_newAddress) {
// Require the WRB is upgradable
require(witnetRequestsBoardInstance.isUpgradable(msg.sender), "The upgrade has been rejected by the current implementation");
// Map the currentLastId to the corresponding witnetRequestsBoardAddress and add it to controllers
controllers.push(ControllerInfo({controllerAddress: _newAddress, lastId: currentLastId}));
// Upgrade the WRB
witnetRequestsBoardAddress = _newAddress;
witnetRequestsBoardInstance = WitnetRequestsBoardInterface(_newAddress);
}
/// @notice Gets the controller from an Id.
/// @param _id id of a Data Request from which we get the controller.
function getController(uint256 _id) internal view returns(address _controllerAddress, uint256 _offset) {
// Check id is bigger than 0
require(_id > 0, "Non-existent controller for id 0");
uint256 n = controllers.length;
// If the id is bigger than the lastId of a Controller, read the result in that Controller
for (uint i = n; i > 0; i--) {
if (_id > controllers[i - 1].lastId) {
return (controllers[i - 1].controllerAddress, controllers[i - 1].lastId);
}
}
}
}
// File: witnet-ethereum-bridge/contracts/BufferLib.sol
/**
* @title A convenient wrapper around the `bytes memory` type that exposes a buffer-like interface
* @notice The buffer has an inner cursor that tracks the final offset of every read, i.e. any subsequent read will
* start with the byte that goes right after the last one in the previous read.
* @dev `uint32` is used here for `cursor` because `uint16` would only enable seeking up to 8KB, which could in some
* theoretical use cases be exceeded. Conversely, `uint32` supports up to 512MB, which cannot credibly be exceeded.
*/
library BufferLib {
struct Buffer {
bytes data;
uint32 cursor;
}
// Ensures we access an existing index in an array
modifier notOutOfBounds(uint32 index, uint256 length) {
require(index < length, "Tried to read from a consumed Buffer (must rewind it first)");
_;
}
/**
* @notice Read and consume a certain amount of bytes from the buffer.
* @param _buffer An instance of `BufferLib.Buffer`.
* @param _length How many bytes to read and consume from the buffer.
* @return A `bytes memory` containing the first `_length` bytes from the buffer, counting from the cursor position.
*/
function read(Buffer memory _buffer, uint32 _length) internal pure returns (bytes memory) {
// Make sure not to read out of the bounds of the original bytes
require(_buffer.cursor + _length <= _buffer.data.length, "Not enough bytes in buffer when reading");
// Create a new `bytes memory destination` value
bytes memory destination = new bytes(_length);
bytes memory source = _buffer.data;
uint32 offset = _buffer.cursor;
// Get raw pointers for source and destination
uint sourcePointer;
uint destinationPointer;
assembly {
sourcePointer := add(add(source, 32), offset)
destinationPointer := add(destination, 32)
}
// Copy `_length` bytes from source to destination
memcpy(destinationPointer, sourcePointer, uint(_length));
// Move the cursor forward by `_length` bytes
seek(_buffer, _length, true);
return destination;
}
/**
* @notice Read and consume the next byte from the buffer.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The next byte in the buffer counting from the cursor position.
*/
function next(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (byte) {
// Return the byte at the position marked by the cursor and advance the cursor all at once
return _buffer.data[_buffer.cursor++];
}
/**
* @notice Move the inner cursor of the buffer to a relative or absolute position.
* @param _buffer An instance of `BufferLib.Buffer`.
* @param _offset How many bytes to move the cursor forward.
* @param _relative Whether to count `_offset` from the last position of the cursor (`true`) or the beginning of the
* buffer (`true`).
* @return The final position of the cursor (will equal `_offset` if `_relative` is `false`).
*/
// solium-disable-next-line security/no-assign-params
function seek(Buffer memory _buffer, uint32 _offset, bool _relative) internal pure returns (uint32) {
// Deal with relative offsets
if (_relative) {
require(_offset + _buffer.cursor > _offset, "Integer overflow when seeking");
_offset += _buffer.cursor;
}
// Make sure not to read out of the bounds of the original bytes
require(_offset <= _buffer.data.length, "Not enough bytes in buffer when seeking");
_buffer.cursor = _offset;
return _buffer.cursor;
}
/**
* @notice Move the inner cursor a number of bytes forward.
* @dev This is a simple wrapper around the relative offset case of `seek()`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @param _relativeOffset How many bytes to move the cursor forward.
* @return The final position of the cursor.
*/
function seek(Buffer memory _buffer, uint32 _relativeOffset) internal pure returns (uint32) {
return seek(_buffer, _relativeOffset, true);
}
/**
* @notice Move the inner cursor back to the first byte in the buffer.
* @param _buffer An instance of `BufferLib.Buffer`.
*/
function rewind(Buffer memory _buffer) internal pure {
_buffer.cursor = 0;
}
/**
* @notice Read and consume the next byte from the buffer as an `uint8`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint8` value of the next byte in the buffer counting from the cursor position.
*/
function readUint8(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (uint8) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint8 value;
assembly {
value := mload(add(add(bytesValue, 1), offset))
}
_buffer.cursor++;
return value;
}
/**
* @notice Read and consume the next 2 bytes from the buffer as an `uint16`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint16` value of the next 2 bytes in the buffer counting from the cursor position.
*/
function readUint16(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 1, _buffer.data.length) returns (uint16) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint16 value;
assembly {
value := mload(add(add(bytesValue, 2), offset))
}
_buffer.cursor += 2;
return value;
}
/**
* @notice Read and consume the next 4 bytes from the buffer as an `uint32`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position.
*/
function readUint32(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 3, _buffer.data.length) returns (uint32) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint32 value;
assembly {
value := mload(add(add(bytesValue, 4), offset))
}
_buffer.cursor += 4;
return value;
}
/**
* @notice Read and consume the next 8 bytes from the buffer as an `uint64`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint64` value of the next 8 bytes in the buffer counting from the cursor position.
*/
function readUint64(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 7, _buffer.data.length) returns (uint64) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint64 value;
assembly {
value := mload(add(add(bytesValue, 8), offset))
}
_buffer.cursor += 8;
return value;
}
/**
* @notice Read and consume the next 16 bytes from the buffer as an `uint128`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint128` value of the next 16 bytes in the buffer counting from the cursor position.
*/
function readUint128(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 15, _buffer.data.length) returns (uint128) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint128 value;
assembly {
value := mload(add(add(bytesValue, 16), offset))
}
_buffer.cursor += 16;
return value;
}
/**
* @notice Read and consume the next 32 bytes from the buffer as an `uint256`.
* @return The `uint256` value of the next 32 bytes in the buffer counting from the cursor position.
* @param _buffer An instance of `BufferLib.Buffer`.
*/
function readUint256(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 31, _buffer.data.length) returns (uint256) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint256 value;
assembly {
value := mload(add(add(bytesValue, 32), offset))
}
_buffer.cursor += 32;
return value;
}
/**
* @notice Read and consume the next 2 bytes from the buffer as an IEEE 754-2008 floating point number enclosed in an
* `int32`.
* @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values
* by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `float16`
* use cases. In other words, the integer output of this method is 10,000 times the actual value. The input bytes are
* expected to follow the 16-bit base-2 format (a.k.a. `binary16`) in the IEEE 754-2008 standard.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position.
*/
function readFloat16(Buffer memory _buffer) internal pure returns (int32) {
uint32 bytesValue = readUint16(_buffer);
// Get bit at position 0
uint32 sign = bytesValue & 0x8000;
// Get bits 1 to 5, then normalize to the [-14, 15] range so as to counterweight the IEEE 754 exponent bias
int32 exponent = (int32(bytesValue & 0x7c00) >> 10) - 15;
// Get bits 6 to 15
int32 significand = int32(bytesValue & 0x03ff);
// Add 1024 to the fraction if the exponent is 0
if (exponent == 15) {
significand |= 0x400;
}
// Compute `2 ^ exponent · (1 + fraction / 1024)`
int32 result = 0;
if (exponent >= 0) {
result = int32(((1 << uint256(exponent)) * 10000 * (uint256(significand) | 0x400)) >> 10);
} else {
result = int32((((uint256(significand) | 0x400) * 10000) / (1 << uint256(- exponent))) >> 10);
}
// Make the result negative if the sign bit is not 0
if (sign != 0) {
result *= - 1;
}
return result;
}
/**
* @notice Copy bytes from one memory address into another.
* @dev This function was borrowed from Nick Johnson's `solidity-stringutils` lib, and reproduced here under the terms
* of [Apache License 2.0](https://github.com/Arachnid/solidity-stringutils/blob/master/LICENSE).
* @param _dest Address of the destination memory.
* @param _src Address to the source memory.
* @param _len How many bytes to copy.
*/
// solium-disable-next-line security/no-assign-params
function memcpy(uint _dest, uint _src, uint _len) private pure {
// Copy word-length chunks while possible
for (; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
}
// File: witnet-ethereum-bridge/contracts/CBOR.sol
/**
* @title A minimalistic implementation of “RFC 7049 Concise Binary Object Representation”
* @notice This library leverages a buffer-like structure for step-by-step decoding of bytes so as to minimize
* the gas cost of decoding them into a useful native type.
* @dev Most of the logic has been borrowed from Patrick Gansterer’s cbor.js library: https://github.com/paroga/cbor-js
* TODO: add support for Array (majorType = 4)
* TODO: add support for Map (majorType = 5)
* TODO: add support for Float32 (majorType = 7, additionalInformation = 26)
* TODO: add support for Float64 (majorType = 7, additionalInformation = 27)
*/
library CBOR {
using BufferLib for BufferLib.Buffer;
uint64 constant internal UINT64_MAX = ~uint64(0);
struct Value {
BufferLib.Buffer buffer;
uint8 initialByte;
uint8 majorType;
uint8 additionalInformation;
uint64 len;
uint64 tag;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `bytes` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as a `bytes` value.
*/
function decodeBytes(Value memory _cborValue) public pure returns(bytes memory) {
_cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation);
if (_cborValue.len == UINT64_MAX) {
bytes memory bytesData;
// These checks look repetitive but the equivalent loop would be more expensive.
uint32 itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType));
if (itemLength < UINT64_MAX) {
bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength));
itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType));
if (itemLength < UINT64_MAX) {
bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength));
}
}
return bytesData;
} else {
return _cborValue.buffer.read(uint32(_cborValue.len));
}
}
/**
* @notice Decode a `CBOR.Value` structure into a `fixed16` value.
* @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values
* by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`
* use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128` value.
*/
function decodeFixed16(Value memory _cborValue) public pure returns(int32) {
require(_cborValue.majorType == 7, "Tried to read a `fixed` value from a `CBOR.Value` with majorType != 7");
require(_cborValue.additionalInformation == 25, "Tried to read `fixed16` from a `CBOR.Value` with additionalInformation != 25");
return _cborValue.buffer.readFloat16();
}
/**
* @notice Decode a `CBOR.Value` structure into a native `int128[]` value whose inner values follow the same convention.
* as explained in `decodeFixed16`.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128[]` value.
*/
function decodeFixed16Array(Value memory _cborValue) public pure returns(int128[] memory) {
require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
int128[] memory array = new int128[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeFixed16(item);
}
return array;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `int128` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128` value.
*/
function decodeInt128(Value memory _cborValue) public pure returns(int128) {
if (_cborValue.majorType == 1) {
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
return int128(-1) - int128(length);
} else if (_cborValue.majorType == 0) {
// Any `uint64` can be safely casted to `int128`, so this method supports majorType 1 as well so as to have offer
// a uniform API for positive and negative numbers
return int128(decodeUint64(_cborValue));
}
revert("Tried to read `int128` from a `CBOR.Value` with majorType not 0 or 1");
}
/**
* @notice Decode a `CBOR.Value` structure into a native `int128[]` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128[]` value.
*/
function decodeInt128Array(Value memory _cborValue) public pure returns(int128[] memory) {
require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
int128[] memory array = new int128[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeInt128(item);
}
return array;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `string` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as a `string` value.
*/
function decodeString(Value memory _cborValue) public pure returns(string memory) {
_cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation);
if (_cborValue.len == UINT64_MAX) {
bytes memory textData;
bool done;
while (!done) {
uint64 itemLength = readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType);
if (itemLength < UINT64_MAX) {
textData = abi.encodePacked(textData, readText(_cborValue.buffer, itemLength / 4));
} else {
done = true;
}
}
return string(textData);
} else {
return string(readText(_cborValue.buffer, _cborValue.len));
}
}
/**
* @notice Decode a `CBOR.Value` structure into a native `string[]` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `string[]` value.
*/
function decodeStringArray(Value memory _cborValue) public pure returns(string[] memory) {
require(_cborValue.majorType == 4, "Tried to read `string[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
string[] memory array = new string[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeString(item);
}
return array;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `uint64` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `uint64` value.
*/
function decodeUint64(Value memory _cborValue) public pure returns(uint64) {
require(_cborValue.majorType == 0, "Tried to read `uint64` from a `CBOR.Value` with majorType != 0");
return readLength(_cborValue.buffer, _cborValue.additionalInformation);
}
/**
* @notice Decode a `CBOR.Value` structure into a native `uint64[]` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `uint64[]` value.
*/
function decodeUint64Array(Value memory _cborValue) public pure returns(uint64[] memory) {
require(_cborValue.majorType == 4, "Tried to read `uint64[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
uint64[] memory array = new uint64[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeUint64(item);
}
return array;
}
/**
* @notice Decode a CBOR.Value structure from raw bytes.
* @dev This is the main factory for CBOR.Value instances, which can be later decoded into native EVM types.
* @param _cborBytes Raw bytes representing a CBOR-encoded value.
* @return A `CBOR.Value` instance containing a partially decoded value.
*/
function valueFromBytes(bytes memory _cborBytes) public pure returns(Value memory) {
BufferLib.Buffer memory buffer = BufferLib.Buffer(_cborBytes, 0);
return valueFromBuffer(buffer);
}
/**
* @notice Decode a CBOR.Value structure from raw bytes.
* @dev This is an alternate factory for CBOR.Value instances, which can be later decoded into native EVM types.
* @param _buffer A Buffer structure representing a CBOR-encoded value.
* @return A `CBOR.Value` instance containing a partially decoded value.
*/
function valueFromBuffer(BufferLib.Buffer memory _buffer) public pure returns(Value memory) {
require(_buffer.data.length > 0, "Found empty buffer when parsing CBOR value");
uint8 initialByte;
uint8 majorType = 255;
uint8 additionalInformation;
uint64 length;
uint64 tag = UINT64_MAX;
bool isTagged = true;
while (isTagged) {
// Extract basic CBOR properties from input bytes
initialByte = _buffer.readUint8();
majorType = initialByte >> 5;
additionalInformation = initialByte & 0x1f;
// Early CBOR tag parsing.
if (majorType == 6) {
tag = readLength(_buffer, additionalInformation);
} else {
isTagged = false;
}
}
require(majorType <= 7, "Invalid CBOR major type");
return CBOR.Value(
_buffer,
initialByte,
majorType,
additionalInformation,
length,
tag);
}
// Reads the length of the next CBOR item from a buffer, consuming a different number of bytes depending on the
// value of the `additionalInformation` argument.
function readLength(BufferLib.Buffer memory _buffer, uint8 additionalInformation) private pure returns(uint64) {
if (additionalInformation < 24) {
return additionalInformation;
}
if (additionalInformation == 24) {
return _buffer.readUint8();
}
if (additionalInformation == 25) {
return _buffer.readUint16();
}
if (additionalInformation == 26) {
return _buffer.readUint32();
}
if (additionalInformation == 27) {
return _buffer.readUint64();
}
if (additionalInformation == 31) {
return UINT64_MAX;
}
revert("Invalid length encoding (non-existent additionalInformation value)");
}
// Read the length of a CBOR indifinite-length item (arrays, maps, byte strings and text) from a buffer, consuming
// as many bytes as specified by the first byte.
function readIndefiniteStringLength(BufferLib.Buffer memory _buffer, uint8 majorType) private pure returns(uint64) {
uint8 initialByte = _buffer.readUint8();
if (initialByte == 0xff) {
return UINT64_MAX;
}
uint64 length = readLength(_buffer, initialByte & 0x1f);
require(length < UINT64_MAX && (initialByte >> 5) == majorType, "Invalid indefinite length");
return length;
}
// Read a text string of a given length from a buffer. Returns a `bytes memory` value for the sake of genericness,
// but it can be easily casted into a string with `string(result)`.
// solium-disable-next-line security/no-assign-params
function readText(BufferLib.Buffer memory _buffer, uint64 _length) private pure returns(bytes memory) {
bytes memory result;
for (uint64 index = 0; index < _length; index++) {
uint8 value = _buffer.readUint8();
if (value & 0x80 != 0) {
if (value < 0xe0) {
value = (value & 0x1f) << 6 |
(_buffer.readUint8() & 0x3f);
_length -= 1;
} else if (value < 0xf0) {
value = (value & 0x0f) << 12 |
(_buffer.readUint8() & 0x3f) << 6 |
(_buffer.readUint8() & 0x3f);
_length -= 2;
} else {
value = (value & 0x0f) << 18 |
(_buffer.readUint8() & 0x3f) << 12 |
(_buffer.readUint8() & 0x3f) << 6 |
(_buffer.readUint8() & 0x3f);
_length -= 3;
}
}
result = abi.encodePacked(result, value);
}
return result;
}
}
// File: witnet-ethereum-bridge/contracts/Witnet.sol
/**
* @title A library for decoding Witnet request results
* @notice The library exposes functions to check the Witnet request success.
* and retrieve Witnet results from CBOR values into solidity types.
*/
library Witnet {
using CBOR for CBOR.Value;
/*
STRUCTS
*/
struct Result {
bool success;
CBOR.Value cborValue;
}
/*
ENUMS
*/
enum ErrorCodes {
// 0x00: Unknown error. Something went really bad!
Unknown,
// Script format errors
/// 0x01: At least one of the source scripts is not a valid CBOR-encoded value.
SourceScriptNotCBOR,
/// 0x02: The CBOR value decoded from a source script is not an Array.
SourceScriptNotArray,
/// 0x03: The Array value decoded form a source script is not a valid RADON script.
SourceScriptNotRADON,
/// Unallocated
ScriptFormat0x04,
ScriptFormat0x05,
ScriptFormat0x06,
ScriptFormat0x07,
ScriptFormat0x08,
ScriptFormat0x09,
ScriptFormat0x0A,
ScriptFormat0x0B,
ScriptFormat0x0C,
ScriptFormat0x0D,
ScriptFormat0x0E,
ScriptFormat0x0F,
// Complexity errors
/// 0x10: The request contains too many sources.
RequestTooManySources,
/// 0x11: The script contains too many calls.
ScriptTooManyCalls,
/// Unallocated
Complexity0x12,
Complexity0x13,
Complexity0x14,
Complexity0x15,
Complexity0x16,
Complexity0x17,
Complexity0x18,
Complexity0x19,
Complexity0x1A,
Complexity0x1B,
Complexity0x1C,
Complexity0x1D,
Complexity0x1E,
Complexity0x1F,
// Operator errors
/// 0x20: The operator does not exist.
UnsupportedOperator,
/// Unallocated
Operator0x21,
Operator0x22,
Operator0x23,
Operator0x24,
Operator0x25,
Operator0x26,
Operator0x27,
Operator0x28,
Operator0x29,
Operator0x2A,
Operator0x2B,
Operator0x2C,
Operator0x2D,
Operator0x2E,
Operator0x2F,
// Retrieval-specific errors
/// 0x30: At least one of the sources could not be retrieved, but returned HTTP error.
HTTP,
/// 0x31: Retrieval of at least one of the sources timed out.
RetrievalTimeout,
/// Unallocated
Retrieval0x32,
Retrieval0x33,
Retrieval0x34,
Retrieval0x35,
Retrieval0x36,
Retrieval0x37,
Retrieval0x38,
Retrieval0x39,
Retrieval0x3A,
Retrieval0x3B,
Retrieval0x3C,
Retrieval0x3D,
Retrieval0x3E,
Retrieval0x3F,
// Math errors
/// 0x40: Math operator caused an underflow.
Underflow,
/// 0x41: Math operator caused an overflow.
Overflow,
/// 0x42: Tried to divide by zero.
DivisionByZero,
Size
}
/*
Result impl's
*/
/**
* @notice Decode raw CBOR bytes into a Result instance.
* @param _cborBytes Raw bytes representing a CBOR-encoded value.
* @return A `Result` instance.
*/
function resultFromCborBytes(bytes calldata _cborBytes) external pure returns(Result memory) {
CBOR.Value memory cborValue = CBOR.valueFromBytes(_cborBytes);
return resultFromCborValue(cborValue);
}
/**
* @notice Decode a CBOR value into a Result instance.
* @param _cborValue An instance of `CBOR.Value`.
* @return A `Result` instance.
*/
function resultFromCborValue(CBOR.Value memory _cborValue) public pure returns(Result memory) {
// Witnet uses CBOR tag 39 to represent RADON error code identifiers.
// [CBOR tag 39] Identifiers for CBOR: https://github.com/lucas-clemente/cbor-specs/blob/master/id.md
bool success = _cborValue.tag != 39;
return Result(success, _cborValue);
}
/**
* @notice Tell if a Result is successful.
* @param _result An instance of Result.
* @return `true` if successful, `false` if errored.
*/
function isOk(Result memory _result) public pure returns(bool) {
return _result.success;
}
/**
* @notice Tell if a Result is errored.
* @param _result An instance of Result.
* @return `true` if errored, `false` if successful.
*/
function isError(Result memory _result) public pure returns(bool) {
return !_result.success;
}
/**
* @notice Decode a bytes value from a Result as a `bytes` value.
* @param _result An instance of Result.
* @return The `bytes` decoded from the Result.
*/
function asBytes(Result memory _result) public pure returns(bytes memory) {
require(_result.success, "Tried to read bytes value from errored Result");
return _result.cborValue.decodeBytes();
}
/**
* @notice Decode an error code from a Result as a member of `ErrorCodes`.
* @param _result An instance of `Result`.
* @return The `CBORValue.Error memory` decoded from the Result.
*/
function asErrorCode(Result memory _result) public pure returns(ErrorCodes) {
uint64[] memory error = asRawError(_result);
return supportedErrorOrElseUnknown(error[0]);
}
/**
* @notice Generate a suitable error message for a member of `ErrorCodes` and its corresponding arguments.
* @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function
* @param _result An instance of `Result`.
* @return A tuple containing the `CBORValue.Error memory` decoded from the `Result`, plus a loggable error message.
*/
function asErrorMessage(Result memory _result) public pure returns(ErrorCodes, string memory) {
uint64[] memory error = asRawError(_result);
ErrorCodes errorCode = supportedErrorOrElseUnknown(error[0]);
bytes memory errorMessage;
if (errorCode == ErrorCodes.SourceScriptNotCBOR) {
errorMessage = abi.encodePacked("Source script #", utoa(error[1]), " was not a valid CBOR value");
} else if (errorCode == ErrorCodes.SourceScriptNotArray) {
errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not an Array of calls");
} else if (errorCode == ErrorCodes.SourceScriptNotRADON) {
errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not a valid RADON script");
} else if (errorCode == ErrorCodes.RequestTooManySources) {
errorMessage = abi.encodePacked("The request contained too many sources (", utoa(error[1]), ")");
} else if (errorCode == ErrorCodes.ScriptTooManyCalls) {
errorMessage = abi.encodePacked(
"Script #",
utoa(error[2]),
" from the ",
stageName(error[1]),
" stage contained too many calls (",
utoa(error[3]),
")"
);
} else if (errorCode == ErrorCodes.UnsupportedOperator) {
errorMessage = abi.encodePacked(
"Operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage is not supported"
);
} else if (errorCode == ErrorCodes.HTTP) {
errorMessage = abi.encodePacked(
"Source #",
utoa(error[1]),
" could not be retrieved. Failed with HTTP error code: ",
utoa(error[2] / 100),
utoa(error[2] % 100 / 10),
utoa(error[2] % 10)
);
} else if (errorCode == ErrorCodes.RetrievalTimeout) {
errorMessage = abi.encodePacked(
"Source #",
utoa(error[1]),
" could not be retrieved because of a timeout."
);
} else if (errorCode == ErrorCodes.Underflow) {
errorMessage = abi.encodePacked(
"Underflow at operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage"
);
} else if (errorCode == ErrorCodes.Overflow) {
errorMessage = abi.encodePacked(
"Overflow at operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage"
);
} else if (errorCode == ErrorCodes.DivisionByZero) {
errorMessage = abi.encodePacked(
"Division by zero at operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage"
);
} else {
errorMessage = abi.encodePacked("Unknown error (0x", utohex(error[0]), ")");
}
return (errorCode, string(errorMessage));
}
/**
* @notice Decode a raw error from a `Result` as a `uint64[]`.
* @param _result An instance of `Result`.
* @return The `uint64[]` raw error as decoded from the `Result`.
*/
function asRawError(Result memory _result) public pure returns(uint64[] memory) {
require(!_result.success, "Tried to read error code from successful Result");
return _result.cborValue.decodeUint64Array();
}
/**
* @notice Decode a fixed16 (half-precision) numeric value from a Result as an `int32` value.
* @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values.
* by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`.
* use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`.
* @param _result An instance of Result.
* @return The `int128` decoded from the Result.
*/
function asFixed16(Result memory _result) public pure returns(int32) {
require(_result.success, "Tried to read `fixed16` value from errored Result");
return _result.cborValue.decodeFixed16();
}
/**
* @notice Decode an array of fixed16 values from a Result as an `int128[]` value.
* @param _result An instance of Result.
* @return The `int128[]` decoded from the Result.
*/
function asFixed16Array(Result memory _result) public pure returns(int128[] memory) {
require(_result.success, "Tried to read `fixed16[]` value from errored Result");
return _result.cborValue.decodeFixed16Array();
}
/**
* @notice Decode a integer numeric value from a Result as an `int128` value.
* @param _result An instance of Result.
* @return The `int128` decoded from the Result.
*/
function asInt128(Result memory _result) public pure returns(int128) {
require(_result.success, "Tried to read `int128` value from errored Result");
return _result.cborValue.decodeInt128();
}
/**
* @notice Decode an array of integer numeric values from a Result as an `int128[]` value.
* @param _result An instance of Result.
* @return The `int128[]` decoded from the Result.
*/
function asInt128Array(Result memory _result) public pure returns(int128[] memory) {
require(_result.success, "Tried to read `int128[]` value from errored Result");
return _result.cborValue.decodeInt128Array();
}
/**
* @notice Decode a string value from a Result as a `string` value.
* @param _result An instance of Result.
* @return The `string` decoded from the Result.
*/
function asString(Result memory _result) public pure returns(string memory) {
require(_result.success, "Tried to read `string` value from errored Result");
return _result.cborValue.decodeString();
}
/**
* @notice Decode an array of string values from a Result as a `string[]` value.
* @param _result An instance of Result.
* @return The `string[]` decoded from the Result.
*/
function asStringArray(Result memory _result) public pure returns(string[] memory) {
require(_result.success, "Tried to read `string[]` value from errored Result");
return _result.cborValue.decodeStringArray();
}
/**
* @notice Decode a natural numeric value from a Result as a `uint64` value.
* @param _result An instance of Result.
* @return The `uint64` decoded from the Result.
*/
function asUint64(Result memory _result) public pure returns(uint64) {
require(_result.success, "Tried to read `uint64` value from errored Result");
return _result.cborValue.decodeUint64();
}
/**
* @notice Decode an array of natural numeric values from a Result as a `uint64[]` value.
* @param _result An instance of Result.
* @return The `uint64[]` decoded from the Result.
*/
function asUint64Array(Result memory _result) public pure returns(uint64[] memory) {
require(_result.success, "Tried to read `uint64[]` value from errored Result");
return _result.cborValue.decodeUint64Array();
}
/**
* @notice Convert a stage index number into the name of the matching Witnet request stage.
* @param _stageIndex A `uint64` identifying the index of one of the Witnet request stages.
* @return The name of the matching stage.
*/
function stageName(uint64 _stageIndex) public pure returns(string memory) {
if (_stageIndex == 0) {
return "retrieval";
} else if (_stageIndex == 1) {
return "aggregation";
} else if (_stageIndex == 2) {
return "tally";
} else {
return "unknown";
}
}
/**
* @notice Get an `ErrorCodes` item from its `uint64` discriminant, or default to `ErrorCodes.Unknown` if it doesn't
* exist.
* @param _discriminant The numeric identifier of an error.
* @return A member of `ErrorCodes`.
*/
function supportedErrorOrElseUnknown(uint64 _discriminant) private pure returns(ErrorCodes) {
if (_discriminant < uint8(ErrorCodes.Size)) {
return ErrorCodes(_discriminant);
} else {
return ErrorCodes.Unknown;
}
}
/**
* @notice Convert a `uint64` into a 1, 2 or 3 characters long `string` representing its.
* three less significant decimal values.
* @param _u A `uint64` value.
* @return The `string` representing its decimal value.
*/
function utoa(uint64 _u) private pure returns(string memory) {
if (_u < 10) {
bytes memory b1 = new bytes(1);
b1[0] = byte(uint8(_u) + 48);
return string(b1);
} else if (_u < 100) {
bytes memory b2 = new bytes(2);
b2[0] = byte(uint8(_u / 10) + 48);
b2[1] = byte(uint8(_u % 10) + 48);
return string(b2);
} else {
bytes memory b3 = new bytes(3);
b3[0] = byte(uint8(_u / 100) + 48);
b3[1] = byte(uint8(_u % 100 / 10) + 48);
b3[2] = byte(uint8(_u % 10) + 48);
return string(b3);
}
}
/**
* @notice Convert a `uint64` into a 2 characters long `string` representing its two less significant hexadecimal values.
* @param _u A `uint64` value.
* @return The `string` representing its hexadecimal value.
*/
function utohex(uint64 _u) private pure returns(string memory) {
bytes memory b2 = new bytes(2);
uint8 d0 = uint8(_u / 16) + 48;
uint8 d1 = uint8(_u % 16) + 48;
if (d0 > 57)
d0 += 7;
if (d1 > 57)
d1 += 7;
b2[0] = byte(d0);
b2[1] = byte(d1);
return string(b2);
}
}
// File: witnet-ethereum-bridge/contracts/Request.sol
/**
* @title The serialized form of a Witnet data request
*/
contract Request {
bytes public bytecode;
uint256 public id;
/**
* @dev A `Request` is constructed around a `bytes memory` value containing a well-formed Witnet data request serialized
* using Protocol Buffers. However, we cannot verify its validity at this point. This implies that contracts using
* the WRB should not be considered trustless before a valid Proof-of-Inclusion has been posted for the requests.
* The hash of the request is computed in the constructor to guarantee consistency. Otherwise there could be a
* mismatch and a data request could be resolved with the result of another.
* @param _bytecode Witnet request in bytes.
*/
constructor(bytes memory _bytecode) public {
bytecode = _bytecode;
id = uint256(sha256(_bytecode));
}
}
// File: witnet-ethereum-bridge/contracts/UsingWitnet.sol
/**
* @title The UsingWitnet contract
* @notice Contract writers can inherit this contract in order to create requests for the
* Witnet network.
*/
contract UsingWitnet {
using Witnet for Witnet.Result;
WitnetRequestsBoardProxy internal wrb;
/**
* @notice Include an address to specify the WitnetRequestsBoard.
* @param _wrb WitnetRequestsBoard address.
*/
constructor(address _wrb) public {
wrb = WitnetRequestsBoardProxy(_wrb);
}
// Provides a convenient way for client contracts extending this to block the execution of the main logic of the
// contract until a particular request has been successfully accepted into Witnet
modifier witnetRequestAccepted(uint256 _id) {
require(witnetCheckRequestAccepted(_id), "Witnet request is not yet accepted into the Witnet network");
_;
}
// Ensures that user-specified rewards are equal to the total transaction value to prevent users from burning any excess value
modifier validRewards(uint256 _requestReward, uint256 _resultReward) {
require(_requestReward + _resultReward >= _requestReward, "The sum of rewards overflows");
require(msg.value == _requestReward + _resultReward, "Transaction value should equal the sum of rewards");
_;
}
/**
* @notice Send a new request to the Witnet network
* @dev Call to `post_dr` function in the WitnetRequestsBoard contract
* @param _request An instance of the `Request` contract
* @param _requestReward Reward specified for the user which posts the request into Witnet
* @param _resultReward Reward specified for the user which posts back the request result
* @return Sequencial identifier for the request included in the WitnetRequestsBoard
*/
function witnetPostRequest(Request _request, uint256 _requestReward, uint256 _resultReward)
internal
validRewards(_requestReward, _resultReward)
returns (uint256)
{
return wrb.postDataRequest.value(_requestReward + _resultReward)(_request.bytecode(), _resultReward);
}
/**
* @notice Check if a request has been accepted into Witnet.
* @dev Contracts depending on Witnet should not start their main business logic (e.g. receiving value from third.
* parties) before this method returns `true`.
* @param _id The sequential identifier of a request that has been previously sent to the WitnetRequestsBoard.
* @return A boolean telling if the request has been already accepted or not. `false` do not mean rejection, though.
*/
function witnetCheckRequestAccepted(uint256 _id) internal view returns (bool) {
// Find the request in the
uint256 drHash = wrb.readDrHash(_id);
// If the hash of the data request transaction in Witnet is not the default, then it means that inclusion of the
// request has been proven to the WRB.
return drHash != 0;
}
/**
* @notice Upgrade the rewards for a Data Request previously included.
* @dev Call to `upgrade_dr` function in the WitnetRequestsBoard contract.
* @param _id The sequential identifier of a request that has been previously sent to the WitnetRequestsBoard.
* @param _requestReward Reward specified for the user which posts the request into Witnet
* @param _resultReward Reward specified for the user which post the Data Request result.
*/
function witnetUpgradeRequest(uint256 _id, uint256 _requestReward, uint256 _resultReward)
internal
validRewards(_requestReward, _resultReward)
{
wrb.upgradeDataRequest.value(msg.value)(_id, _resultReward);
}
/**
* @notice Read the result of a resolved request.
* @dev Call to `read_result` function in the WitnetRequestsBoard contract.
* @param _id The sequential identifier of a request that was posted to Witnet.
* @return The result of the request as an instance of `Result`.
*/
function witnetReadResult(uint256 _id) internal view returns (Witnet.Result memory) {
return Witnet.resultFromCborBytes(wrb.readResult(_id));
}
}
// File: adomedianizer/contracts/IERC2362.sol
/**
* @dev EIP2362 Interface for pull oracles
* https://github.com/tellor-io/EIP-2362
*/
interface IERC2362
{
/**
* @dev Exposed function pertaining to EIP standards
* @param _id bytes32 ID of the query
* @return int,uint,uint returns the value, timestamp, and status code of query
*/
function valueFor(bytes32 _id) external view returns(int256,uint256,uint256);
}
// File: witnet-price-feeds-examples/contracts/requests/BitcoinPrice.sol
// The bytecode of the BitcoinPrice request that will be sent to Witnet
contract BitcoinPriceRequest is Request {
constructor () Request(hex"0abb0108c3aafbf405123b122468747470733a2f2f7777772e6269747374616d702e6e65742f6170692f7469636b65722f1a13841877821864646c6173748218571903e8185b125c123168747470733a2f2f6170692e636f696e6465736b2e636f6d2f76312f6270692f63757272656e7470726963652e6a736f6e1a2786187782186663627069821866635553448218646a726174655f666c6f61748218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { }
}
// File: witnet-price-feeds-examples/contracts/bitcoin_price_feed/BtcUsdPriceFeed.sol
// Import the UsingWitnet library that enables interacting with Witnet
// Import the ERC2362 interface
// Import the BitcoinPrice request that you created before
// Your contract needs to inherit from UsingWitnet
contract BtcUsdPriceFeed is UsingWitnet, IERC2362 {
// The public Bitcoin price point
uint64 public lastPrice;
// Stores the ID of the last Witnet request
uint256 public lastRequestId;
// Stores the timestamp of the last time the public price point was updated
uint256 public timestamp;
// Tells if an update has been requested but not yet completed
bool public pending;
// The Witnet request object, is set in the constructor
Request public request;
// Emits when the price is updated
event priceUpdated(uint64);
// Emits when found an error decoding request result
event resultError(string);
// This is `keccak256("Price-BTC/USD-3")`
bytes32 constant public BTCUSD3ID = bytes32(hex"637b7efb6b620736c247aaa282f3898914c0bef6c12faff0d3fe9d4bea783020");
// This constructor does a nifty trick to tell the `UsingWitnet` library where
// to find the Witnet contracts on whatever Ethereum network you use.
constructor (address _wrb) UsingWitnet(_wrb) public {
// Instantiate the Witnet request
request = new BitcoinPriceRequest();
}
/**
* @notice Sends `request` to the WitnetRequestsBoard.
* @dev This method will only succeed if `pending` is 0.
**/
function requestUpdate() public payable {
require(!pending, "An update is already pending. Complete it first before requesting another update.");
// Amount to pay to the bridge node relaying this request from Ethereum to Witnet
uint256 _witnetRequestReward = 100 szabo;
// Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum
uint256 _witnetResultReward = 100 szabo;
// Send the request to Witnet and store the ID for later retrieval of the result
// The `witnetPostRequest` method comes with `UsingWitnet`
lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward);
// Signal that there is already a pending request
pending = true;
}
/**
* @notice Reads the result, if ready, from the WitnetRequestsBoard.
* @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to
* protect your methods from being called before the request has been successfully
* relayed into Witnet.
**/
function completeUpdate() public witnetRequestAccepted(lastRequestId) {
require(pending, "There is no pending update.");
// Read the result of the Witnet request
// The `witnetReadResult` method comes with `UsingWitnet`
Witnet.Result memory result = witnetReadResult(lastRequestId);
// If the Witnet request succeeded, decode the result and update the price point
// If it failed, revert the transaction with a pretty-printed error message
if (result.isOk()) {
lastPrice = result.asUint64();
timestamp = block.timestamp;
emit priceUpdated(lastPrice);
} else {
string memory errorMessage;
// Try to read the value as an error message, catch error bytes if read fails
try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) {
errorMessage = e;
}
catch (bytes memory errorBytes){
errorMessage = string(errorBytes);
}
emit resultError(errorMessage);
}
// In any case, set `pending` to false so a new update can be requested
pending = false;
}
/**
* @notice Exposes the public data point in an ERC2362 compliant way.
* @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called
* successfully before.
**/
function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) {
// Unsupported data point ID
if(_id != BTCUSD3ID) return(0, 0, 400);
// No value is yet available for the queried data point ID
if (timestamp == 0) return(0, 0, 404);
int256 value = int256(lastPrice);
return(value, timestamp, 200);
}
}
// File: witnet-price-feeds-examples/contracts/requests/EthPrice.sol
// The bytecode of the EthPrice request that will be sent to Witnet
contract EthPriceRequest is Request {
constructor () Request(hex"0a850208d7affbf4051245122e68747470733a2f2f7777772e6269747374616d702e6e65742f6170692f76322f7469636b65722f6574687573642f1a13841877821864646c6173748218571903e8185b1247122068747470733a2f2f6170692e636f696e6361702e696f2f76322f6173736574731a238618778218616464617461821818018218646870726963655573648218571903e8185b1253122668747470733a2f2f6170692e636f696e70617072696b612e636f6d2f76312f7469636b6572731a29871876821818038218666671756f746573821866635553448218646570726963658218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { }
}
// File: witnet-price-feeds-examples/contracts/eth_price_feed/EthUsdPriceFeed.sol
// Import the UsingWitnet library that enables interacting with Witnet
// Import the ERC2362 interface
// Import the ethPrice request that you created before
// Your contract needs to inherit from UsingWitnet
contract EthUsdPriceFeed is UsingWitnet, IERC2362 {
// The public eth price point
uint64 public lastPrice;
// Stores the ID of the last Witnet request
uint256 public lastRequestId;
// Stores the timestamp of the last time the public price point was updated
uint256 public timestamp;
// Tells if an update has been requested but not yet completed
bool public pending;
// The Witnet request object, is set in the constructor
Request public request;
// Emits when the price is updated
event priceUpdated(uint64);
// Emits when found an error decoding request result
event resultError(string);
// This is the ERC2362 identifier for a eth price feed, computed as `keccak256("Price-ETH/USD-3")`
bytes32 constant public ETHUSD3ID = bytes32(hex"dfaa6f747f0f012e8f2069d6ecacff25f5cdf0258702051747439949737fc0b5");
// This constructor does a nifty trick to tell the `UsingWitnet` library where
// to find the Witnet contracts on whatever Ethereum network you use.
constructor (address _wrb) UsingWitnet(_wrb) public {
// Instantiate the Witnet request
request = new EthPriceRequest();
}
/**
* @notice Sends `request` to the WitnetRequestsBoard.
* @dev This method will only succeed if `pending` is 0.
**/
function requestUpdate() public payable {
require(!pending, "An update is already pending. Complete it first before requesting another update.");
// Amount to pay to the bridge node relaying this request from Ethereum to Witnet
uint256 _witnetRequestReward = 100 szabo;
// Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum
uint256 _witnetResultReward = 100 szabo;
// Send the request to Witnet and store the ID for later retrieval of the result
// The `witnetPostRequest` method comes with `UsingWitnet`
lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward);
// Signal that there is already a pending request
pending = true;
}
/**
* @notice Reads the result, if ready, from the WitnetRequestsBoard.
* @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to
* protect your methods from being called before the request has been successfully
* relayed into Witnet.
**/
function completeUpdate() public witnetRequestAccepted(lastRequestId) {
require(pending, "There is no pending update.");
// Read the result of the Witnet request
// The `witnetReadResult` method comes with `UsingWitnet`
Witnet.Result memory result = witnetReadResult(lastRequestId);
// If the Witnet request succeeded, decode the result and update the price point
// If it failed, revert the transaction with a pretty-printed error message
if (result.isOk()) {
lastPrice = result.asUint64();
timestamp = block.timestamp;
emit priceUpdated(lastPrice);
} else {
string memory errorMessage;
// Try to read the value as an error message, catch error bytes if read fails
try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) {
errorMessage = e;
}
catch (bytes memory errorBytes){
errorMessage = string(errorBytes);
}
emit resultError(errorMessage);
}
// In any case, set `pending` to false so a new update can be requested
pending = false;
}
/**
* @notice Exposes the public data point in an ERC2362 compliant way.
* @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called
* successfully before.
**/
function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) {
// Unsupported data point ID
if(_id != ETHUSD3ID) return(0, 0, 400);
// No value is yet available for the queried data point ID
if (timestamp == 0) return(0, 0, 404);
int256 value = int256(lastPrice);
return(value, timestamp, 200);
}
}
// File: witnet-price-feeds-examples/contracts/requests/GoldPrice.sol
// The bytecode of the GoldPrice request that will be sent to Witnet
contract GoldPriceRequest is Request {
constructor () Request(hex"0ab90308c3aafbf4051257123f68747470733a2f2f636f696e7965702e636f6d2f6170692f76312f3f66726f6d3d58415526746f3d455552266c616e673d657326666f726d61743d6a736f6e1a148418778218646570726963658218571903e8185b1253122b68747470733a2f2f646174612d6173672e676f6c6470726963652e6f72672f64625852617465732f4555521a24861877821861656974656d73821818008218646878617550726963658218571903e8185b1255123668747470733a2f2f7777772e6d7963757272656e63797472616e736665722e636f6d2f6170692f63757272656e742f5841552f4555521a1b851877821866646461746182186464726174658218571903e8185b129101125d68747470733a2f2f7777772e696e766572736f726f2e65732f6461746f732f3f706572696f643d3379656172267869676e6974655f636f64653d5841552663757272656e63793d455552267765696768745f756e69743d6f756e6365731a308518778218666a7461626c655f64617461821864736d6574616c5f70726963655f63757272656e748218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { }
}
// File: witnet-price-feeds-examples/contracts/gold_price_feed/GoldEurPriceFeed.sol
// Import the UsingWitnet library that enables interacting with Witnet
// Import the ERC2362 interface
// Import the goldPrice request that you created before
// Your contract needs to inherit from UsingWitnet
contract GoldEurPriceFeed is UsingWitnet, IERC2362 {
// The public gold price point
uint64 public lastPrice;
// Stores the ID of the last Witnet request
uint256 public lastRequestId;
// Stores the timestamp of the last time the public price point was updated
uint256 public timestamp;
// Tells if an update has been requested but not yet completed
bool public pending;
// The Witnet request object, is set in the constructor
Request public request;
// Emits when the price is updated
event priceUpdated(uint64);
// Emits when found an error decoding request result
event resultError(string);
// This is the ERC2362 identifier for a gold price feed, computed as `keccak256("Price-XAU/EUR-3")`
bytes32 constant public XAUEUR3ID = bytes32(hex"68cba0705475e40c1ddbf7dc7c1ae4e7320ca094c4e118d1067c4dea5df28590");
// This constructor does a nifty trick to tell the `UsingWitnet` library where
// to find the Witnet contracts on whatever Ethereum network you use.
constructor (address _wrb) UsingWitnet(_wrb) public {
// Instantiate the Witnet request
request = new GoldPriceRequest();
}
/**
* @notice Sends `request` to the WitnetRequestsBoard.
* @dev This method will only succeed if `pending` is 0.
**/
function requestUpdate() public payable {
require(!pending, "An update is already pending. Complete it first before requesting another update.");
// Amount to pay to the bridge node relaying this request from Ethereum to Witnet
uint256 _witnetRequestReward = 100 szabo;
// Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum
uint256 _witnetResultReward = 100 szabo;
// Send the request to Witnet and store the ID for later retrieval of the result
// The `witnetPostRequest` method comes with `UsingWitnet`
lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward);
// Signal that there is already a pending request
pending = true;
}
/**
* @notice Reads the result, if ready, from the WitnetRequestsBoard.
* @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to
* protect your methods from being called before the request has been successfully
* relayed into Witnet.
**/
function completeUpdate() public witnetRequestAccepted(lastRequestId) {
require(pending, "There is no pending update.");
// Read the result of the Witnet request
// The `witnetReadResult` method comes with `UsingWitnet`
Witnet.Result memory result = witnetReadResult(lastRequestId);
// If the Witnet request succeeded, decode the result and update the price point
// If it failed, revert the transaction with a pretty-printed error message
if (result.isOk()) {
lastPrice = result.asUint64();
timestamp = block.timestamp;
emit priceUpdated(lastPrice);
} else {
string memory errorMessage;
// Try to read the value as an error message, catch error bytes if read fails
try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) {
errorMessage = e;
}
catch (bytes memory errorBytes){
errorMessage = string(errorBytes);
}
emit resultError(errorMessage);
}
// In any case, set `pending` to false so a new update can be requested
pending = false;
}
/**
* @notice Exposes the public data point in an ERC2362 compliant way.
* @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called
* successfully before.
**/
function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) {
// Unsupported data point ID
if(_id != XAUEUR3ID) return(0, 0, 400);
// No value is yet available for the queried data point ID
if (timestamp == 0) return(0, 0, 404);
int256 value = int256(lastPrice);
return(value, timestamp, 200);
}
}
// File: contracts/Deployer.sol
// Import witnet-ethereum-block-relay-contracts
// Import the UsingWitnet library that enables interacting with Witnet
// Import price feeds
contract Deployer {
}
// File: contracts/Migrations.sol
contract Migrations {
address public owner;
uint public lastCompletedMigration;
constructor() public {
owner = msg.sender;
}
modifier restricted() {
if (msg.sender == owner)
_;
}
function setCompleted(uint _completed) public restricted {
lastCompletedMigration = _completed;
}
function upgrade(address _newAddress) public restricted {
Migrations upgraded = Migrations(_newAddress);
upgraded.setCompleted(lastCompletedMigration);
}
}
| * @notice Read and consume the next 32 bytes from the buffer as an `uint256`. @return The `uint256` value of the next 32 bytes in the buffer counting from the cursor position. @param _buffer An instance of `BufferLib.Buffer`./ | function readUint256(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 31, _buffer.data.length) returns (uint256) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint256 value;
assembly {
value := mload(add(add(bytesValue, 32), offset))
}
_buffer.cursor += 32;
return value;
}
| 901,207 | [
1,
1994,
471,
7865,
326,
1024,
3847,
1731,
628,
326,
1613,
487,
392,
1375,
11890,
5034,
8338,
327,
1021,
1375,
11890,
5034,
68,
460,
434,
326,
1024,
3847,
1731,
316,
326,
1613,
22075,
628,
326,
3347,
1754,
18,
225,
389,
4106,
1922,
791,
434,
1375,
1892,
5664,
18,
1892,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
225,
445,
855,
5487,
5034,
12,
1892,
3778,
389,
4106,
13,
2713,
16618,
486,
11224,
5694,
24899,
4106,
18,
9216,
397,
8231,
16,
389,
4106,
18,
892,
18,
2469,
13,
1135,
261,
11890,
5034,
13,
288,
203,
565,
1731,
3778,
1731,
620,
273,
389,
4106,
18,
892,
31,
203,
565,
2254,
1578,
1384,
273,
389,
4106,
18,
9216,
31,
203,
565,
2254,
5034,
460,
31,
203,
565,
19931,
288,
203,
1377,
460,
519,
312,
945,
12,
1289,
12,
1289,
12,
3890,
620,
16,
3847,
3631,
1384,
3719,
203,
565,
289,
203,
565,
389,
4106,
18,
9216,
1011,
3847,
31,
203,
203,
565,
327,
460,
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
]
|
./full_match/80001/0xc04e87bCd09B1821db562fc2f5748DD193713a67/sources/contracts/TradeableCashflow.sol | public variables which we'll set userData values to | ISuperfluid.Context public uData;
| 9,464,078 | [
1,
482,
3152,
1492,
732,
5614,
444,
13530,
924,
358,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
467,
8051,
2242,
1911,
18,
1042,
1071,
582,
751,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/3/0x32c949e1cC06BCb1E0d4e27F028416fE5a687269/sources/crowdfunding.sol | function gets product Id and wallet address of producer as parameter and returns order details
| function getProductbyId(address _addr, int _pid) view public returns (int, int, string memory, bool) { | 14,207,013 | [
1,
915,
5571,
3017,
3124,
471,
9230,
1758,
434,
12608,
487,
1569,
471,
1135,
1353,
3189,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
445,
15880,
1637,
548,
12,
2867,
389,
4793,
16,
509,
389,
6610,
13,
1476,
1071,
1135,
261,
474,
16,
509,
16,
533,
3778,
16,
1426,
13,
288,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/IRuntime.sol";
import "./libraries/Firewall.sol";
import "./libraries/Revert.sol";
/// @title Runtime
/// @notice Executes transactions and deploys contracts for the DAO.
contract Runtime is IRuntime, Firewall {
/// @inheritdoc IRuntime
function predict(bytes32 bytecodehash, bytes32 salt) external view returns (address) {
return address(
uint160(
uint256(
keccak256(
abi.encodePacked(
bytes1(0xff),
address(this),
salt,
bytecodehash
)
)
)
)
);
}
/// @inheritdoc IRuntime
function create(bytes memory bytecode) external returns (address deployment) {
require(bytecode.length > 0, "BytecodeZero");
assembly { deployment := create(0, add(bytecode, 32), mload(bytecode)) }
require(deployment != address(0), "DeployFailed");
emit Create(deployment);
}
/// @inheritdoc IRuntime
function create2(bytes memory bytecode, bytes32 salt) external returns (address deployment) {
require(bytecode.length > 0, "BytecodeZero");
assembly { deployment := create2(0, add(bytecode, 32), mload(bytecode), salt) }
require(deployment != address(0), "DeployFailed");
emit Create2(deployment);
}
/// @inheritdoc IRuntime
function call(address target, bytes calldata data) external {
(bool success, bytes memory returndata) = target.call(data);
if (!success) {
revert(Revert.getRevertMsg(returndata));
}
emit Call(target, data);
}
/// @inheritdoc IRuntime
function execute(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
string calldata message
) external returns (bytes[] memory results) {
require(targets.length == values.length, "Mismatch");
require(targets.length == datas.length, "Mismatch");
results = new bytes[](targets.length);
for (uint256 i = 0; i < targets.length; i++) {
bool success;
if (targets[i] != address(this)) {
(success, results[i]) = targets[i].call{value: values[i]}(datas[i]);
} else if (targets[i] == address(this)) {
(success, results[i]) = address(this).delegatecall(datas[i]);
}
if (!success) {
revert(Revert.getRevertMsg(results[i]));
}
}
emit Executed(keccak256(abi.encode(targets, values, datas, message)), message);
}
}
| @title Runtime @notice Executes transactions and deploys contracts for the DAO. | contract Runtime is IRuntime, Firewall {
pragma solidity ^0.8.0;
function predict(bytes32 bytecodehash, bytes32 salt) external view returns (address) {
return address(
uint160(
uint256(
keccak256(
abi.encodePacked(
bytes1(0xff),
address(this),
salt,
bytecodehash
)
)
)
)
);
}
function create(bytes memory bytecode) external returns (address deployment) {
require(bytecode.length > 0, "BytecodeZero");
require(deployment != address(0), "DeployFailed");
emit Create(deployment);
}
assembly { deployment := create(0, add(bytecode, 32), mload(bytecode)) }
function create2(bytes memory bytecode, bytes32 salt) external returns (address deployment) {
require(bytecode.length > 0, "BytecodeZero");
require(deployment != address(0), "DeployFailed");
emit Create2(deployment);
}
assembly { deployment := create2(0, add(bytecode, 32), mload(bytecode), salt) }
function call(address target, bytes calldata data) external {
(bool success, bytes memory returndata) = target.call(data);
if (!success) {
revert(Revert.getRevertMsg(returndata));
}
emit Call(target, data);
}
function call(address target, bytes calldata data) external {
(bool success, bytes memory returndata) = target.call(data);
if (!success) {
revert(Revert.getRevertMsg(returndata));
}
emit Call(target, data);
}
function execute(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
string calldata message
) external returns (bytes[] memory results) {
require(targets.length == values.length, "Mismatch");
require(targets.length == datas.length, "Mismatch");
results = new bytes[](targets.length);
for (uint256 i = 0; i < targets.length; i++) {
bool success;
if (targets[i] != address(this)) {
(success, results[i]) = address(this).delegatecall(datas[i]);
}
if (!success) {
revert(Revert.getRevertMsg(results[i]));
}
}
emit Executed(keccak256(abi.encode(targets, values, datas, message)), message);
}
function execute(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
string calldata message
) external returns (bytes[] memory results) {
require(targets.length == values.length, "Mismatch");
require(targets.length == datas.length, "Mismatch");
results = new bytes[](targets.length);
for (uint256 i = 0; i < targets.length; i++) {
bool success;
if (targets[i] != address(this)) {
(success, results[i]) = address(this).delegatecall(datas[i]);
}
if (!success) {
revert(Revert.getRevertMsg(results[i]));
}
}
emit Executed(keccak256(abi.encode(targets, values, datas, message)), message);
}
function execute(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
string calldata message
) external returns (bytes[] memory results) {
require(targets.length == values.length, "Mismatch");
require(targets.length == datas.length, "Mismatch");
results = new bytes[](targets.length);
for (uint256 i = 0; i < targets.length; i++) {
bool success;
if (targets[i] != address(this)) {
(success, results[i]) = address(this).delegatecall(datas[i]);
}
if (!success) {
revert(Revert.getRevertMsg(results[i]));
}
}
emit Executed(keccak256(abi.encode(targets, values, datas, message)), message);
}
(success, results[i]) = targets[i].call{value: values[i]}(datas[i]);
} else if (targets[i] == address(this)) {
function execute(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
string calldata message
) external returns (bytes[] memory results) {
require(targets.length == values.length, "Mismatch");
require(targets.length == datas.length, "Mismatch");
results = new bytes[](targets.length);
for (uint256 i = 0; i < targets.length; i++) {
bool success;
if (targets[i] != address(this)) {
(success, results[i]) = address(this).delegatecall(datas[i]);
}
if (!success) {
revert(Revert.getRevertMsg(results[i]));
}
}
emit Executed(keccak256(abi.encode(targets, values, datas, message)), message);
}
}
| 2,560,262 | [
1,
5576,
225,
3889,
993,
8938,
471,
5993,
383,
1900,
20092,
364,
326,
463,
20463,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
2509,
353,
467,
5576,
16,
22829,
288,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
565,
445,
7810,
12,
3890,
1578,
22801,
2816,
16,
1731,
1578,
4286,
13,
3903,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
1758,
12,
203,
5411,
2254,
16874,
12,
203,
7734,
2254,
5034,
12,
203,
10792,
417,
24410,
581,
5034,
12,
203,
13491,
24126,
18,
3015,
4420,
329,
12,
203,
18701,
1731,
21,
12,
20,
5297,
3631,
203,
18701,
1758,
12,
2211,
3631,
203,
18701,
4286,
16,
203,
18701,
22801,
2816,
203,
13491,
262,
203,
10792,
262,
203,
7734,
262,
203,
5411,
262,
203,
3639,
11272,
203,
565,
289,
203,
203,
565,
445,
752,
12,
3890,
3778,
22801,
13,
3903,
1135,
261,
2867,
6314,
13,
288,
203,
3639,
2583,
12,
1637,
16651,
18,
2469,
405,
374,
16,
315,
858,
16651,
7170,
8863,
203,
3639,
2583,
12,
21704,
480,
1758,
12,
20,
3631,
315,
10015,
2925,
8863,
203,
203,
3639,
3626,
1788,
12,
21704,
1769,
203,
565,
289,
203,
203,
3639,
19931,
288,
6314,
519,
752,
12,
20,
16,
527,
12,
1637,
16651,
16,
3847,
3631,
312,
945,
12,
1637,
16651,
3719,
289,
203,
565,
445,
752,
22,
12,
3890,
3778,
22801,
16,
1731,
1578,
4286,
13,
3903,
1135,
261,
2867,
6314,
13,
288,
203,
3639,
2583,
12,
1637,
16651,
18,
2469,
405,
374,
16,
315,
858,
16651,
7170,
8863,
203,
3639,
2583,
12,
21704,
480,
1758,
12,
20,
3631,
315,
10015,
2925,
8863,
203,
203,
3639,
3626,
1788,
22,
12,
21704,
1769,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
// File: @chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol
/*
* @dev Provides o consume price data, this smart contract references
* AggregatorV3Interface, which defines the external functions implemented by
* the ETH/USD Price Feed.
*/
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// File: @openzeppelin/contracts/utils/Context.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), 'Ownable: caller is not the owner');
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), 'Ownable: new owner is the zero address');
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/utils/introspection/IERC1820Registry.sol
/**
* @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);
}
// File: @openzeppelin/contracts/utils/Address.sol
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, 'Address: insufficient balance');
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}('');
require(
success,
'Address: unable to send value, recipient may have reverted'
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, 'Address: low-level call failed');
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
'Address: low-level call with value failed'
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
'Address: insufficient balance for call'
);
require(isContract(target), 'Address: call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(target, data, 'Address: low-level static call failed');
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), 'Address: static call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
'Address: low-level delegate call failed'
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), 'Address: delegate call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/token/ERC777/IERC777Sender.sol
/**
* @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;
}
// File: @openzeppelin/contracts/token/ERC777/IERC777Recipient.sol
/**
* @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;
}
// File: @openzeppelin/contracts/token/ERC777/IERC777.sol
/**
* @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);
}
// File: @openzeppelin/contracts/token/ERC777/ERC777.sol
/**
* @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 Address for address;
IERC1820Registry internal constant _ERC1820_REGISTRY =
IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
bytes32 private constant _TOKENS_SENDER_INTERFACE_HASH =
keccak256('ERC777TokensSender');
bytes32 private constant _TOKENS_RECIPIENT_INTERFACE_HASH =
keccak256('ERC777TokensRecipient');
// 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_
) {
_name = name_;
_symbol = symbol_;
_defaultOperatorsArray = defaultOperators_;
for (uint256 i = 0; i < defaultOperators_.length; i++) {
_defaultOperators[defaultOperators_[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 virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() public view virtual 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 virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() public view virtual override returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply()
public
view
virtual
override(IERC20, IERC777)
returns (uint256)
{
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by an account (`tokenHolder`).
*/
function balanceOf(address tokenHolder)
public
view
virtual
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 virtual 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
virtual
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 virtual override {
_burn(_msgSender(), amount, data, '');
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(address operator, address tokenHolder)
public
view
virtual
override
returns (bool)
{
return
operator == tokenHolder ||
(_defaultOperators[operator] &&
!_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) public virtual 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 virtual 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
virtual
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 virtual 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 virtual 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
virtual
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
virtual
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 virtual 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, '', '');
uint256 currentAllowance = _allowances[holder][spender];
require(
currentAllowance >= amount,
'ERC777: transfer amount exceeds allowance'
);
_approve(holder, spender, currentAllowance - amount);
_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 {
_mint(account, amount, userData, operatorData, true);
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If `requireReceptionAck` is set to true, and 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,
bool requireReceptionAck
) 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 += amount;
_balances[account] += amount;
_callTokensReceived(
operator,
address(0),
account,
amount,
userData,
operatorData,
requireReceptionAck
);
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 virtual {
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();
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
_beforeTokenTransfer(operator, from, address(0), amount);
// Update state variables
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, 'ERC777: burn amount exceeds balance');
_balances[from] = fromBalance - amount;
_totalSupply -= 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);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, 'ERC777: transfer amount exceeds balance');
_balances[from] = fromBalance - amount;
_balances[to] += 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 {}
}
// File: contracts/5_MDSToken.sol
// Library: SafeDecimalMath (Synthetix)
/**
* @title Safely manipulate unsigned fixed-point decimals at a given precision level.
* @dev Functions accepting uints in this contract and derived contracts
* are taken to be such fixed point decimals of a specified precision (either standard
* or high).
*/
library SafeDecimalMath {
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
/* The number representing 1.0. */
uint256 public constant UNIT = 10**uint256(decimals);
/* The number representing 1.0 for higher fidelity numbers. */
uint256 public constant PRECISE_UNIT = 10**uint256(highPrecisionDecimals);
uint256 private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR =
10**uint256(highPrecisionDecimals - decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint256) {
return UNIT;
}
/**
* @return Provides an interface to PRECISE_UNIT.
*/
function preciseUnit() external pure returns (uint256) {
return PRECISE_UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256. As this is an integer division,
* the internal division always rounds down. This helps save on gas. Rounding
* is more expensive on gas.
*/
function multiplyDecimal(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
/* Divide by UNIT to remove the extra factor introduced by the product. */
return (x * y) / UNIT;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of the specified precision unit.
*
* @dev The operands should be in the form of a the specified unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function _multiplyDecimalRound(
uint256 x,
uint256 y,
uint256 precisionUnit
) private pure returns (uint256) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
uint256 quotientTimesTen = (x * y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a precise unit.
*
* @dev The operands should be in the precise unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRoundPrecise(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a standard unit.
*
* @dev The operands should be in the standard unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRound(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return _multiplyDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint256 x, uint256 y) internal pure returns (uint256) {
/* Reintroduce the UNIT factor that will be divided out by y. */
return (x * UNIT) / y;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* decimal in the precision unit specified in the parameter.
*
* @dev y is divided after the product of x and the specified precision unit
* is evaluated, so the product of x and the specified precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function _divideDecimalRound(
uint256 x,
uint256 y,
uint256 precisionUnit
) private pure returns (uint256) {
uint256 resultTimesTen = (x * (precisionUnit * 10)) / y;
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* standard precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and the standard precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRound(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return _divideDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* high precision decimal.
*
* @dev y is divided after the product of x and the high precision unit
* is evaluated, so the product of x and the high precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRoundPrecise(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @dev Convert a standard decimal representation to a high precision one.
*/
function decimalToPreciseDecimal(uint256 i) internal pure returns (uint256) {
return i * UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR;
}
/**
* @dev Convert a high precision decimal to a standard decimal representation.
*/
function preciseDecimalToDecimal(uint256 i) internal pure returns (uint256) {
uint256 quotientTimesTen = i /
(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
}
// Library: StringsAndBytes
/**
* @title StringsAndBytes Converts Strings to Bytes and Bytes32 and Vice-versa
* @dev Converting Bytes and Strings into one another
*/
library StringsAndBytes {
function stringToBytes32(string memory _source)
public
pure
returns (bytes32 result)
{
// String have to be max 32 chars
// https://ethereum.stackexchange.com/questions/9603/understanding-mload-assembly-function
// http://solidity.readthedocs.io/en/latest/assembly.html
assembly {
result := mload(add(_source, 32))
}
}
function bytes32ToBytes(bytes32 _bytes32) public pure returns (bytes memory) {
// bytes32 (fixed-size array) to bytes (dynamically-sized array)
// string memory str = string(_bytes32);
// TypeError: Explicit type conversion not allowed from "bytes32" to "string storage pointer"
bytes memory bytesArray = new bytes(32);
for (uint256 i; i < 32; i++) {
bytesArray[i] = _bytes32[i];
}
return bytesArray;
}
function bytes32ToString(bytes32 _bytes32)
public
pure
returns (string memory)
{
// https://ethereum.stackexchange.com/questions/2519/how-to-convert-a-bytes32-to-string
// https://ethereum.stackexchange.com/questions/1081/how-to-concatenate-a-bytes32-array-to-a-string
bytes memory bytesArray = bytes32ToBytes(_bytes32);
return string(bytesArray);
}
}
contract MDSToken is ERC777, Ownable {
using SafeDecimalMath for uint256;
/**
* Network: Rinkeby
* Aggregator: ETH/USD
* Address: 0x8A753747A1Fa494EC906cE90E9f37563A8AF630e
*/
AggregatorV3Interface internal priceFeed;
// This is a type for a single proposal.
struct Person {
bytes32 firstName; // first name (up to 32 bytes)
bytes32 lastName; // last/family name (up to 32 bytes)
uint8 age; // Age
}
// This is a type for a single proposal.
struct Family {
uint256 numberOfMembers; // number of members
uint256 balance; // family balance
address[] membersArray; // array of members
address operator; // person delegated to
}
// This declares a state variable that
// stores a `Family` struct for each familyName.
mapping(bytes32 => Family) public families;
mapping(address => uint256) pendingWithdrawals;
constructor(uint256 initialSupply, address[] memory defaultOperators)
ERC777('MedShare', 'MDST', defaultOperators)
{
priceFeed = AggregatorV3Interface(
0x8A753747A1Fa494EC906cE90E9f37563A8AF630e
);
_mint(msg.sender, initialSupply, '', '');
}
/**
* @dev Mint more tokens when debit or credit is received.
*/
function invest(string memory familyName) public payable {
require(
msg.sender != address(0),
'ERC777: cannot mint to the zero address'
);
// Call returns a boolean value indicating success or failure.
// This is the current recommended method to use.
(bool sent, bytes memory data) = address(this).call{value: msg.value}('');
require(sent, 'Failed to send Ether');
// Exchanging ETH to USD
uint256 usd = (msg.value * uint256(getEthUsdPrice())) /
10**getEthUsdPriceDecimals();
uint256 cached = (usd * 6167) / 100;
uint256 fifth = usd / 5;
uint256 twelfth = (usd * 833) / 100;
uint256 tenth = usd / 10;
bytes32 _familyNameB32 = StringsAndBytes.stringToBytes32(familyName);
families[_familyNameB32].balance += family;
_mint(address(this), fifth, '', '');
_mint(owner, twelfth, '', '');
_mint(msg.sender, cached, '', '');
}
/**
* @dev Mint more tokens when debit or credit is received.
* @param familyName family to where the investiment will go.
*/
function investInAFamily(string memory familyName) public payable {
require(msg.sender != address(0), 'ERC777: mint to the zero address');
uint256 usd = (msg.value * uint256(getEthUsdPrice())) /
10**getEthUsdPriceDecimals();
_mint(msg.sender, usd, '', '');
}
/**
* @dev ClaimFundsFrom Family.
* @param familyName family from where funds can come
* @param amount amount asked to be approved by the family operator
*/
function claimFundsFrom(string memory familyName, uint256 amount) public {
require(msg.sender != address(0), 'ERC777: mint to the zero address');
pendingWithdrawals[msg.sender] += amount;
uint256 usd = (msg.value * uint256(getEthUsdPrice())) /
10**getEthUsdPriceDecimals();
address payable claimant = msg.sender;
address(this).transfer(claimant);
}
function withdraw() public {
uint256 amount = pendingWithdrawals[msg.sender];
// Remember to zero the pending refund before
// sending to prevent re-entrancy attacks
pendingWithdrawals[msg.sender] = 0;
payable(msg.sender).transfer(amount);
}
/**
* Returns the latest price
*/
function getEthUsdPrice() public view returns (int256) {
(
uint80 roundID,
int256 price,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
) = priceFeed.latestRoundData();
return price;
}
function getEthUsdPriceDecimals() public view returns (uint8) {
uint8 decimals = priceFeed.decimals();
return decimals;
}
function getContractBalance() public view returns (uint256) {
return address(this).balance;
}
function sendUSDT(address _to, uint256 _amount) external {
// This is the mainnet USDT contract address
IERC20 usdt = IERC20(address(0xdAC17F958D2ee523a2206206994597C13D831ec7));
// transfers USDT that belong to your contract to the specified address
usdt.transfer(_to, _amount);
}
event Received(address, uint256);
// Function to receive Ether. msg.data must be empty
receive() external payable {
emit Received(msg.sender, msg.value);
}
event Fallenback(address, uint256);
// Fallback function is called when msg.data is not empty
fallback() external payable {
emit Fallenback(msg.sender, msg.value);
}
}
| This is a type for a single proposal. | contract MDSToken is ERC777, Ownable {
using SafeDecimalMath for uint256;
AggregatorV3Interface internal priceFeed;
struct Person {
}
struct Family {
}
mapping(address => uint256) pendingWithdrawals;
constructor(uint256 initialSupply, address[] memory defaultOperators)
ERC777('MedShare', 'MDST', defaultOperators)
mapping(bytes32 => Family) public families;
{
priceFeed = AggregatorV3Interface(
0x8A753747A1Fa494EC906cE90E9f37563A8AF630e
);
_mint(msg.sender, initialSupply, '', '');
}
function invest(string memory familyName) public payable {
require(
msg.sender != address(0),
'ERC777: cannot mint to the zero address'
);
require(sent, 'Failed to send Ether');
uint256 usd = (msg.value * uint256(getEthUsdPrice())) /
10**getEthUsdPriceDecimals();
uint256 cached = (usd * 6167) / 100;
uint256 fifth = usd / 5;
uint256 twelfth = (usd * 833) / 100;
uint256 tenth = usd / 10;
bytes32 _familyNameB32 = StringsAndBytes.stringToBytes32(familyName);
families[_familyNameB32].balance += family;
_mint(address(this), fifth, '', '');
_mint(owner, twelfth, '', '');
_mint(msg.sender, cached, '', '');
}
(bool sent, bytes memory data) = address(this).call{value: msg.value}('');
function investInAFamily(string memory familyName) public payable {
require(msg.sender != address(0), 'ERC777: mint to the zero address');
uint256 usd = (msg.value * uint256(getEthUsdPrice())) /
10**getEthUsdPriceDecimals();
_mint(msg.sender, usd, '', '');
}
function claimFundsFrom(string memory familyName, uint256 amount) public {
require(msg.sender != address(0), 'ERC777: mint to the zero address');
pendingWithdrawals[msg.sender] += amount;
uint256 usd = (msg.value * uint256(getEthUsdPrice())) /
10**getEthUsdPriceDecimals();
address payable claimant = msg.sender;
address(this).transfer(claimant);
}
function withdraw() public {
uint256 amount = pendingWithdrawals[msg.sender];
pendingWithdrawals[msg.sender] = 0;
payable(msg.sender).transfer(amount);
}
function getEthUsdPrice() public view returns (int256) {
(
uint80 roundID,
int256 price,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
) = priceFeed.latestRoundData();
return price;
}
function getEthUsdPriceDecimals() public view returns (uint8) {
uint8 decimals = priceFeed.decimals();
return decimals;
}
function getContractBalance() public view returns (uint256) {
return address(this).balance;
}
function sendUSDT(address _to, uint256 _amount) external {
IERC20 usdt = IERC20(address(0xdAC17F958D2ee523a2206206994597C13D831ec7));
usdt.transfer(_to, _amount);
}
event Received(address, uint256);
receive() external payable {
emit Received(msg.sender, msg.value);
}
event Fallenback(address, uint256);
fallback() external payable {
emit Fallenback(msg.sender, msg.value);
}
}
| 12,574,110 | [
1,
2503,
353,
279,
618,
364,
279,
2202,
14708,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
10852,
882,
969,
353,
4232,
39,
14509,
16,
14223,
6914,
288,
203,
225,
1450,
14060,
5749,
10477,
364,
2254,
5034,
31,
203,
203,
225,
10594,
639,
58,
23,
1358,
2713,
6205,
8141,
31,
203,
203,
225,
1958,
11573,
288,
203,
225,
289,
203,
203,
225,
1958,
19343,
288,
203,
225,
289,
203,
203,
203,
225,
2874,
12,
2867,
516,
2254,
5034,
13,
4634,
1190,
9446,
1031,
31,
203,
203,
225,
3885,
12,
11890,
5034,
2172,
3088,
1283,
16,
1758,
8526,
3778,
805,
24473,
13,
203,
565,
4232,
39,
14509,
2668,
13265,
9535,
2187,
296,
6188,
882,
2187,
805,
24473,
13,
203,
225,
2874,
12,
3890,
1578,
516,
19343,
13,
1071,
25914,
31,
203,
225,
288,
203,
565,
6205,
8141,
273,
10594,
639,
58,
23,
1358,
12,
203,
1377,
374,
92,
28,
37,
5877,
23,
5608,
27,
37,
21,
29634,
7616,
24,
7228,
29,
7677,
71,
41,
9349,
41,
29,
74,
6418,
4313,
23,
37,
28,
6799,
4449,
20,
73,
203,
565,
11272,
203,
565,
389,
81,
474,
12,
3576,
18,
15330,
16,
2172,
3088,
1283,
16,
10226,
23489,
203,
225,
289,
203,
203,
225,
445,
2198,
395,
12,
1080,
3778,
6755,
461,
13,
1071,
8843,
429,
288,
203,
565,
2583,
12,
203,
1377,
1234,
18,
15330,
480,
1758,
12,
20,
3631,
203,
1377,
296,
654,
39,
14509,
30,
2780,
312,
474,
358,
326,
3634,
1758,
11,
203,
565,
11272,
203,
565,
2583,
12,
7569,
16,
296,
2925,
358,
1366,
512,
1136,
8284,
203,
203,
565,
2254,
5034,
584,
72,
273,
261,
3576,
18,
2
]
|
./partial_match/1/0xEb5302954d013483091C5725d5d3Abe5A703A464/sources/src/SellerFinancing.sol | @inheritdoc ISellerFinancingAdmin | function updateSeaportContractAddress(address newSeaportContractAddress) external onlyOwner {
_requireNonZeroAddress(newSeaportContractAddress);
seaportContractAddress = newSeaportContractAddress;
}
| 16,059,660 | [
1,
36,
10093,
467,
22050,
6187,
304,
2822,
4446,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1089,
1761,
438,
499,
8924,
1887,
12,
2867,
394,
1761,
438,
499,
8924,
1887,
13,
3903,
1338,
5541,
288,
203,
3639,
389,
6528,
3989,
7170,
1887,
12,
2704,
1761,
438,
499,
8924,
1887,
1769,
203,
3639,
695,
438,
499,
8924,
1887,
273,
394,
1761,
438,
499,
8924,
1887,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./PoolContributor.sol";
contract BudgetPool {
// State variables
Pool[] public pools;
address public owner;
// Mappings
mapping(string => address) public poolNameToOwner;
mapping(address => string) public ownerToPoolName;
mapping(string => uint256) public poolNameToAmount;
mapping(address => uint256) public poolAddressToAmount;
mapping(string => address[]) public poolNameToPoolContributors;
mapping(address => address[]) public poolToPoolContributors;
// Events
/// @dev Format for Pool's name: [OrganisationName]-[WorkingGroupName]
// (e.g. IndexCoop-Engineering)
struct Pool {
string name;
uint256 amount;
address[] poolContributors;
}
constructor() {
owner = msg.sender;
}
// Adds new Pool to pools array
function addPool(
string memory _name,
uint256 _amount,
address[] memory _poolContributors
) external {
pools.push(Pool(_name, _amount, _poolContributors));
poolNameToOwner[_name] = msg.sender;
ownerToPoolName[msg.sender] = _name;
poolNameToAmount[_name] = _amount;
}
// View functions
function getContractBalance() external view returns (uint256) {
return address(this).balance;
}
function getPoolAmount() external view returns (uint256) {
return poolAddressToAmount[address(this)];
}
fallback() external payable {}
/**
* @notice contract can receive Ether.
*/
receive() external payable {}
}
| Adds new Pool to pools array | function addPool(
string memory _name,
uint256 _amount,
address[] memory _poolContributors
) external {
pools.push(Pool(_name, _amount, _poolContributors));
poolNameToOwner[_name] = msg.sender;
ownerToPoolName[msg.sender] = _name;
poolNameToAmount[_name] = _amount;
}
| 12,964,429 | [
1,
3655,
394,
8828,
358,
16000,
526,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
527,
2864,
12,
203,
3639,
533,
3778,
389,
529,
16,
203,
3639,
2254,
5034,
389,
8949,
16,
203,
3639,
1758,
8526,
3778,
389,
6011,
442,
665,
13595,
203,
565,
262,
3903,
288,
203,
3639,
16000,
18,
6206,
12,
2864,
24899,
529,
16,
389,
8949,
16,
389,
6011,
442,
665,
13595,
10019,
203,
203,
3639,
26445,
774,
5541,
63,
67,
529,
65,
273,
1234,
18,
15330,
31,
203,
3639,
3410,
774,
2864,
461,
63,
3576,
18,
15330,
65,
273,
389,
529,
31,
203,
3639,
26445,
774,
6275,
63,
67,
529,
65,
273,
389,
8949,
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
]
|
./partial_match/1/0xc83d39Ae2a764edd7f674aAfd4f03f7d2CEa0947/sources/ClownsAI.sol | * @dev Required interface of an ERC721 compliant contract./ | interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
| 9,207,173 | [
1,
3705,
1560,
434,
392,
4232,
39,
27,
5340,
24820,
6835,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5831,
467,
654,
39,
27,
5340,
353,
467,
654,
39,
28275,
288,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
8808,
1147,
548,
1769,
203,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
20412,
16,
2254,
5034,
8808,
1147,
548,
1769,
203,
203,
565,
871,
1716,
685,
1125,
1290,
1595,
12,
2867,
8808,
3410,
16,
1758,
8808,
3726,
16,
1426,
20412,
1769,
203,
203,
565,
445,
11013,
951,
12,
2867,
3410,
13,
3903,
1476,
1135,
261,
11890,
5034,
11013,
1769,
203,
203,
565,
445,
3410,
951,
12,
11890,
5034,
1147,
548,
13,
3903,
1476,
1135,
261,
2867,
3410,
1769,
203,
203,
203,
565,
445,
4183,
5912,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
262,
3903,
31,
203,
203,
7010,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
262,
3903,
31,
203,
203,
27699,
565,
445,
6617,
537,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
13,
3903,
31,
203,
203,
21281,
565,
445,
336,
31639,
12,
11890,
5034,
1147,
548,
13,
3903,
1476,
1135,
261,
2867,
3726,
1769,
203,
203,
27699,
565,
445,
444,
23461,
1290,
1595,
12,
2867,
3726,
16,
1426,
389,
25990,
13,
3903,
31,
203,
203,
565,
445,
353,
31639,
1290,
1595,
12,
2867,
3410,
16,
1758,
3726,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
203,
565,
445,
4183,
5912,
2
]
|
/* This line specifies which version of the solidity compiler should be used */
/* a pragma in CS tells how a compiler should process it's input */
/* more details: pragmas are a form of directive, like #define in C */
pragma solidity ^0.4.8;
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
/* checks if modified function is being sent run by owner */
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract MurokCoin is owned {
/* An event allows us to use the EVM logging systems to store arguments in the transaction's logs
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/* Public variables of the token */
string public name;
string public symbol;
uint8 public decimals;
bytes32 public currentChallenge; // The coin starts with a challenge
uint public timeOfLastProof; // Variable to keep track of when rewards were given
uint public difficulty = 10**32; // Difficulty starts reasonably low
/* Creating an array with all balances, all of which are publicly accessible on the blockchain */
mapping (address => uint256) public balanceOf;
function MurokCoin(
uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimalUnits,
address centralMinter
) {
/* this function runs once when a contract is uploaded to the network */
if(centralMinter != 0 ) owner = centralMinter;
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
timeOfLastProof = now;
}
/* Send coins */
function transfer(address _to, uint256 _value) {
/* Check if sender has balance and for overflows */
if (balanceOf[msg.sender] < _value || balanceOf[_to] + _value < balanceOf[_to] )
throw;
/* Add and subtract new balances */
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
/* Notify anyone listening that this transfer took place */
Transfer(msg.sender, _to, _value);
}
/* Reward ether miners with MurokCoins */
function giveBlockReward() {
balanceOf[block.coinbase] += 1;
}
function proofOfWork(uint nonce) {
bytes8 n = bytes8(sha3(nonce, currentChallenge)); // Generate a random hash based on input
if (n < bytes8(difficulty)) throw;
uint timeSinceLastProof = (now - timeOfLastProof); // Calculate time since last reward was given
if (timeSinceLastProof < 5 seconds) throw; // Rewards cannot be given too quickly
balanceOf[msg.sender] += timeSinceLastProof / 60 seconds; // The reward to the winner grows by the minute
difficulty = difficulty * 10 minutes / timeSinceLastProof + 1; // Adjusts the difficulty
timeOfLastProof = now;
currentChallenge = sha3(nonce, currentChallenge, block.blockhash(block.number-1)); // save a hash that will be used as the next proof
}
}
| An event allows us to use the EVM logging systems to store arguments in the transaction's logs/ Public variables of the token */ Creating an array with all balances, all of which are publicly accessible on the blockchain */ | ) {
if(centralMinter != 0 ) owner = centralMinter;
timeOfLastProof = now;
| 15,884,617 | [
1,
979,
871,
5360,
584,
358,
999,
326,
512,
7397,
2907,
14908,
358,
1707,
1775,
316,
326,
2492,
1807,
5963,
19,
7224,
3152,
434,
326,
1147,
342,
21837,
392,
526,
598,
777,
324,
26488,
16,
777,
434,
1492,
854,
1071,
715,
12718,
603,
326,
16766,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
262,
288,
203,
565,
309,
12,
71,
12839,
49,
2761,
480,
374,
262,
3410,
273,
18291,
49,
2761,
31,
203,
565,
813,
951,
3024,
20439,
273,
2037,
31,
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
]
|
./partial_match/1/0x64F4916C3868bA4dF4aF21704C8468bA9646345d/sources/TNTX.sol | ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and an initial fixed supply ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------ | contract TNTX is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function TNTX() public {
symbol = "TNTX";
name = "Trades & Track";
decimals = 18;
_totalSupply = 10 * 10000 * 10000 * 10**uint(decimals);
balances[owner] = _totalSupply;
Transfer(address(0), owner, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function () public payable {
revert();
}
} | 3,898,638 | [
1,
5802,
7620,
4232,
39,
3462,
3155,
16,
598,
326,
2719,
434,
3273,
16,
508,
471,
15105,
471,
392,
2172,
5499,
14467,
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,
399,
1784,
60,
353,
4232,
39,
3462,
1358,
16,
14223,
11748,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
203,
565,
533,
1071,
3273,
31,
203,
565,
533,
1071,
225,
508,
31,
203,
565,
2254,
28,
1071,
15105,
31,
203,
565,
2254,
1071,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
2935,
31,
203,
203,
203,
565,
445,
399,
1784,
60,
1435,
1071,
288,
203,
3639,
3273,
273,
315,
56,
1784,
60,
14432,
203,
3639,
508,
273,
315,
1609,
5489,
473,
11065,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
1728,
380,
12619,
380,
12619,
380,
1728,
636,
11890,
12,
31734,
1769,
203,
3639,
324,
26488,
63,
8443,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
12279,
12,
2867,
12,
20,
3631,
3410,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
5381,
1135,
261,
11890,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
225,
300,
324,
26488,
63,
2867,
12,
20,
13,
15533,
203,
565,
289,
203,
203,
203,
565,
445,
11013,
951,
12,
2867,
1147,
5541,
13,
1071,
5381,
1135,
261,
11890,
11013,
13,
288,
203,
3639,
327,
324,
26488,
63,
2316,
5541,
15533,
203,
565,
289,
203,
203,
203,
565,
445,
7412,
12,
2867,
358,
16,
2254,
2430,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
324,
2
]
|
./partial_match/1/0x0D479207504DB0A947EFc98DaBd4652cE525e463/sources/MainToken.sol | Buying value in Eth < max Eth limit/address buyer, */ | function canBuyToken(
uint256 amount
) private view {
require(
getMainTokenEstimatedPrice(amount) < maxEthUserCanBuy,
"Buy limit exceeded"
);
}
| 9,192,597 | [
1,
38,
9835,
310,
460,
316,
512,
451,
411,
943,
512,
451,
1800,
19,
2867,
27037,
16,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
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,
848,
38,
9835,
1345,
12,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3238,
1476,
288,
203,
3639,
2583,
12,
203,
5411,
15011,
1345,
9122,
17275,
5147,
12,
8949,
13,
411,
943,
41,
451,
1299,
2568,
38,
9835,
16,
203,
5411,
315,
38,
9835,
1800,
12428,
6,
203,
3639,
11272,
203,
565,
289,
203,
202,
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
]
|
./full_match/1/0x0ac5f3d54bAE068BA24910bE99746e3e3a3Ad23e/sources/contracts/SendMainnet/SendIt.sol | * @dev Retrieves appropriate tax rate. functionality: - returns tax rate depending on tier current block is in/ | function getFees() internal {
require(
tradingOpenedOnBlock > 0, "SENDIT ERROR: Trading not live"
);
uint256 currentBlock = block.number;
uint256 lastTierOneBlock = tradingOpenedOnBlock + 10;
uint256 lastTierTwoBlock = tradingOpenedOnBlock + 20;
if(currentBlock <= lastTierOneBlock) {
buyTotalFees = 25;
sellTotalFees = 25;
buyTotalFees = 15;
sellTotalFees = 15;
buyTotalFees = 4;
sellTotalFees = 4;
fetchFees = false;
}
buyMarketingFee = buyTotalFees / 4;
buyTreasuryFee = buyTotalFees / 2;
sellMarketingFee = sellTotalFees / 4;
sellTreasuryFee = sellTotalFees / 2;
}
| 4,911,424 | [
1,
6960,
5505,
5320,
4993,
18,
14176,
30,
300,
1135,
5320,
4993,
8353,
603,
17742,
783,
1203,
353,
316,
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,
13683,
281,
1435,
2713,
288,
203,
3639,
2583,
12,
203,
5411,
1284,
7459,
23115,
1398,
1768,
405,
374,
16,
315,
21675,
1285,
5475,
30,
2197,
7459,
486,
8429,
6,
203,
3639,
11272,
203,
3639,
2254,
5034,
30610,
273,
1203,
18,
2696,
31,
203,
3639,
2254,
5034,
1142,
15671,
3335,
1768,
273,
1284,
7459,
23115,
1398,
1768,
397,
1728,
31,
203,
3639,
2254,
5034,
1142,
15671,
11710,
1768,
273,
1284,
7459,
23115,
1398,
1768,
397,
4200,
31,
203,
3639,
309,
12,
2972,
1768,
1648,
1142,
15671,
3335,
1768,
13,
288,
203,
5411,
30143,
5269,
2954,
281,
273,
6969,
31,
203,
5411,
357,
80,
5269,
2954,
281,
273,
6969,
31,
203,
5411,
30143,
5269,
2954,
281,
273,
4711,
31,
203,
5411,
357,
80,
5269,
2954,
281,
273,
4711,
31,
203,
5411,
30143,
5269,
2954,
281,
273,
1059,
31,
203,
5411,
357,
80,
5269,
2954,
281,
273,
1059,
31,
203,
5411,
2158,
2954,
281,
273,
629,
31,
203,
3639,
289,
203,
3639,
30143,
3882,
21747,
14667,
273,
30143,
5269,
2954,
281,
342,
1059,
31,
203,
3639,
30143,
56,
266,
345,
22498,
14667,
273,
30143,
5269,
2954,
281,
342,
576,
31,
203,
3639,
357,
80,
3882,
21747,
14667,
273,
357,
80,
5269,
2954,
281,
342,
1059,
31,
203,
3639,
357,
80,
56,
266,
345,
22498,
14667,
273,
357,
80,
5269,
2954,
281,
342,
576,
31,
203,
565,
289,
203,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity >=0.4.0 <0.7.0;
import "@chainlink/contracts/src/v0.4/ChainlinkClient.sol";
import "@chainlink/contracts/src/v0.4/vendor/Ownable.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
contract JagerGitClient is ChainlinkClient, Ownable {
uint256 constant private ORACLE_PAYMENT = 1 * LINK;
address _oracle;
string _jobId;
string url1;
string url2;
bytes32 public addrStr;
/**
* @dev Details of each transfer
* @param contract_ contract address of ER20 token to transfer
* @param to_ receiving account
* @param amount_ number of tokens to transfer to_ account
* @param failed_ if transfer was successful or not
*/
struct Transfer {
address contract_;
address to_;
uint amount_;
bool failed_;
}
event requestBountyCompleteFulfilled(
bytes32 indexed requestId,
bytes32 indexed addrStr
);
/**
* @dev a mapping from transaction ID's to the sender address
* that initiates them. Owners can create several transactions
*/
mapping(address => uint[]) public transactionIndexesToSender;
/**
* @dev a list of all transfers successful or unsuccessful
*/
address public owner;
/**
* @dev list of all supported tokens for transfer
* @param string token symbol
* @param address contract address of token
*/
mapping(bytes32 => address) public tokens;
ERC20 public ERC20Interface;
Transfer[] public transactions;
/**
* @dev Event to notify if transfer successful or failed
* after account approval verified
*/
event TransferSuccessful(address indexed from_, address indexed to_, uint256 amount_);
event TransferFailed(address indexed from_, address indexed to_, uint256 amount_);
/**
* @dev add address of token to list of supported tokens using
* token symbol as identifier in mapping
*/
function addNewToken(bytes32 symbol_, address address_) public onlyOwner returns (bool) {
tokens[symbol_] = address_;
return true;
}
/**
* @dev remove address of token we no more support
*/
function removeToken(bytes32 symbol_) public onlyOwner returns (bool) {
require(tokens[symbol_] != 0x0);
delete(tokens[symbol_]);
return true;
}
/**
* @dev method that handles transfer of ERC20 tokens to other address
* it assumes the calling address has approved this contract
* as spender
* @param symbol_ identifier mapping to a token contract address
* @param to_ beneficiary address
* @param amount_ numbers of token to transfer
*/
function transferTokens(bytes32 symbol_, address to_, uint256 amount_) public {
require(tokens[symbol_] != 0x0);
require(amount_ > 0);
address contract_ = tokens[symbol_];
address from_ = msg.sender;
ERC20Interface = ERC20(contract_);
uint256 transactionId = transactions.push(
Transfer({
contract_: contract_,
to_: to_,
amount_: amount_,
failed_: true
})
);
transactionIndexesToSender[from_].push(transactionId - 1);
if(amount_ > ERC20Interface.allowance(from_, address(this))) {
emit TransferFailed(from_, to_, amount_);
revert();
}
ERC20Interface.transferFrom(from_, to_, amount_);
transactions[transactionId - 1].failed_ = false;
emit TransferSuccessful(from_, to_, amount_);
}
/**
* @dev withdraw funds from this contract
* @param beneficiary address to receive ether
*/
function withdraw(address beneficiary) public payable onlyOwner {
beneficiary.transfer(address(this).balance);
}
function cashReward(bytes32 symbol_, address to_, uint256 amount_) public {
require(tokens[symbol_] != 0x0);
require(amount_ > 0);
address contract_ = tokens[symbol_];
ERC20Interface = ERC20(contract_);
uint256 transactionId = transactions.push(
Transfer({
contract_: contract_,
to_: to_,
amount_: amount_,
failed_: true
})
);
if(amount_ > ERC20Interface.balanceOf(address(this))) {
emit TransferFailed(address(this), to_, amount_);
revert();
}
ERC20Interface.transferFrom(address(this), to_, amount_);
transactions[transactionId - 1].failed_ = false;
emit TransferSuccessful(address(this), to_, amount_);
}
uint256 reward_pool;
struct Bounty {
uint id;
string repo_link;
string tag;
uint reward_amount;
bool active;
string title;
string description;
}
struct Meister {
address id;
uint bounties_fulfilled;
}
uint[] public bountyIDs;
address[] public allMeisters;
mapping (address => uint[]) public meister_bounty_ids;
mapping (string => uint[]) private repo_bounties;
mapping (uint => Bounty) public bounties;
event NewBounty(uint _bounty_id, address _owner, uint _reward);
constructor() public Ownable() {
setPublicChainlinkToken();
_oracle = address(0x56dd6586DB0D08c6Ce7B2f2805af28616E082455);
_jobId = "c128fbb0175442c8ba828040fdd1a25e";
bytes32 b = stringToBytes32("DAI");
addNewToken(b, address(0x4dC966317B2c55105FAd4835F651022aCD632120));
url1 = "https://api.github.com/repos/";
url2 = "/pulls/";
}
function AddNewMeister() private {
allMeisters.push(msg.sender);
}
function CreateBounty(string memory repoLink,
uint reward,
string PR_tag,
string title,
string description) public returns (uint bountyID) {
Bounty memory bounty = Bounty({
id: bountyIDs.length,
repo_link: repoLink,
tag: PR_tag,
reward_amount: reward,
active: true,
title: title,
description: description
});
uint len = repo_bounties[repoLink].length;
if(len != 0) {
for(uint i = 0; i < len; i++) {
uint id = repo_bounties[repoLink][i];
require(compare(bounties[id].tag, PR_tag) != 0 || !bounties[id].active);
}
}
repo_bounties[repoLink].push(bounty.id);
if (meister_bounty_ids[msg.sender].length == 0) {
AddNewMeister();
}
meister_bounty_ids[msg.sender].push(bounty.id);
bountyIDs.push(bounty.id);
bounties[bounty.id] = bounty;
return bounty.id;
}
function GetMeisterBounties(address meister) public view returns (uint[] memory bountyIds) {
return meister_bounty_ids[meister];
}
function GetRepoBounties(string repoLink) public view returns (uint[] memory bountyIds) {
return repo_bounties[repoLink];
}
function GetBountyInfo(uint bountyId) public view returns (uint id,
string memory repoLink,
string memory tag,
uint reward,
bool active,
string memory title,
string memory description) {
Bounty memory bounty = bounties[bountyId];
return (bounty.id,
bounty.repo_link,
bounty.tag,
bounty.reward_amount,
bounty.active,
bounty.title,
bounty.description);
}
function getChainlinkToken() public view returns (address) {
return chainlinkTokenAddress();
}
function withdrawLink() public onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer");
}
function cancelRequest(
bytes32 _requestId,
uint256 _payment,
bytes4 _callbackFunctionId,
uint256 _expiration
)
public
onlyOwner
{
cancelChainlinkRequest(_requestId, _payment, _callbackFunctionId, _expiration);
}
function stringToBytes32(string memory source) private pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly { // solhint-disable-line no-inline-assembly
result := mload(add(source, 32))
}
}
function compare(string _a, string _b) private pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
//@todo unroll the loop into increments of 32 and do full 32 byte comparisons
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function requestBountyComplete(string repo_link, string PR_id)
public
onlyOwner
{
Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(_jobId), this, this.fulfillBountyComplete.selector);
req.add("get", string(abi.encodePacked(url1, repo_link, url2, PR_id)));
req.add("path", "body");
sendChainlinkRequestTo(_oracle, req, ORACLE_PAYMENT);
}
function fulfillBountyComplete(bytes32 _requestId, bytes32 _addrStr)
public
recordChainlinkFulfillment(_requestId)
{
emit requestBountyCompleteFulfilled(_requestId, _addrStr);
addrStr = _addrStr;
}
}
| * @dev add address of token to list of supported tokens using token symbol as identifier in mapping/ | function addNewToken(bytes32 symbol_, address address_) public onlyOwner returns (bool) {
tokens[symbol_] = address_;
return true;
}
| 999,047 | [
1,
1289,
1758,
434,
1147,
358,
666,
434,
3260,
2430,
1450,
1147,
3273,
487,
2756,
316,
2874,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
20973,
1345,
12,
3890,
1578,
3273,
67,
16,
1758,
1758,
67,
13,
1071,
1338,
5541,
1135,
261,
6430,
13,
288,
21281,
565,
2430,
63,
7175,
67,
65,
273,
1758,
67,
31,
21281,
377,
203,
565,
327,
638,
31,
21281,
225,
289,
21281,
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
]
|
pragma solidity ^0.6.6;
pragma experimental ABIEncoderV2;
import './Ownable.sol';
import './SafeMath.sol';
import './Address.sol';
import './ACONameFormatter.sol';
import './ACOAssetHelper.sol';
import './ERC20.sol';
import './IACOPool.sol';
import './IACOFactory.sol';
import './IACOStrategy.sol';
import './IACOToken.sol';
import './IACOFlashExercise.sol';
import './IUniswapV2Router02.sol';
import './IChiToken.sol';
/**
* @title ACOPool
* @dev A pool contract to trade ACO tokens.
*/
contract ACOPool is Ownable, ERC20, IACOPool {
using Address for address;
using SafeMath for uint256;
uint256 internal constant POOL_PRECISION = 1000000000000000000; // 18 decimals
uint256 internal constant MAX_UINT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/**
* @dev Struct to store an ACO token trade data.
*/
struct ACOTokenData {
/**
* @dev Amount of tokens sold by the pool.
*/
uint256 amountSold;
/**
* @dev Amount of tokens purchased by the pool.
*/
uint256 amountPurchased;
/**
* @dev Index of the ACO token on the stored array.
*/
uint256 index;
}
/**
* @dev Emitted when the strategy address has been changed.
* @param oldStrategy Address of the previous strategy.
* @param newStrategy Address of the new strategy.
*/
event SetStrategy(address indexed oldStrategy, address indexed newStrategy);
/**
* @dev Emitted when the base volatility has been changed.
* @param oldBaseVolatility Value of the previous base volatility.
* @param newBaseVolatility Value of the new base volatility.
*/
event SetBaseVolatility(uint256 indexed oldBaseVolatility, uint256 indexed newBaseVolatility);
/**
* @dev Emitted when a collateral has been deposited on the pool.
* @param account Address of the account.
* @param amount Amount deposited.
*/
event CollateralDeposited(address indexed account, uint256 amount);
/**
* @dev Emitted when the collateral and premium have been redeemed on the pool.
* @param account Address of the account.
* @param underlyingAmount Amount of underlying asset redeemed.
* @param strikeAssetAmount Amount of strike asset redeemed.
*/
event Redeem(address indexed account, uint256 underlyingAmount, uint256 strikeAssetAmount);
/**
* @dev Emitted when the collateral has been restored on the pool.
* @param amountOut Amount of the premium sold.
* @param collateralIn Amount of collateral restored.
*/
event RestoreCollateral(uint256 amountOut, uint256 collateralIn);
/**
* @dev Emitted when an ACO token has been redeemed.
* @param acoToken Address of the ACO token.
* @param collateralIn Amount of collateral redeemed.
* @param amountSold Total amount of ACO token sold by the pool.
* @param amountPurchased Total amount of ACO token purchased by the pool.
*/
event ACORedeem(address indexed acoToken, uint256 collateralIn, uint256 amountSold, uint256 amountPurchased);
/**
* @dev Emitted when an ACO token has been exercised.
* @param acoToken Address of the ACO token.
* @param tokenAmount Amount of ACO tokens exercised.
* @param collateralIn Amount of collateral received.
*/
event ACOExercise(address indexed acoToken, uint256 tokenAmount, uint256 collateralIn);
/**
* @dev Emitted when an ACO token has been bought or sold by the pool.
* @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying.
* @param account Address of the account that is doing the swap.
* @param acoToken Address of the ACO token.
* @param tokenAmount Amount of ACO tokens swapped.
* @param price Value of the premium paid in strike asset.
* @param protocolFee Value of the protocol fee paid in strike asset.
* @param underlyingPrice The underlying price in strike asset.
*/
event Swap(
bool indexed isPoolSelling,
address indexed account,
address indexed acoToken,
uint256 tokenAmount,
uint256 price,
uint256 protocolFee,
uint256 underlyingPrice
);
/**
* @dev UNIX timestamp that the pool can start to trade ACO tokens.
*/
uint256 public poolStart;
/**
* @dev The protocol fee percentage. (100000 = 100%)
*/
uint256 public fee;
/**
* @dev Address of the ACO flash exercise contract.
*/
IACOFlashExercise public acoFlashExercise;
/**
* @dev Address of the ACO factory contract.
*/
IACOFactory public acoFactory;
/**
* @dev Address of the Uniswap V2 router.
*/
IUniswapV2Router02 public uniswapRouter;
/**
* @dev Address of the Chi gas token.
*/
IChiToken public chiToken;
/**
* @dev Address of the protocol fee destination.
*/
address public feeDestination;
/**
* @dev Address of the underlying asset accepts by the pool.
*/
address public underlying;
/**
* @dev Address of the strike asset accepts by the pool.
*/
address public strikeAsset;
/**
* @dev Value of the minimum strike price on ACO token that the pool accept to trade.
*/
uint256 public minStrikePrice;
/**
* @dev Value of the maximum strike price on ACO token that the pool accept to trade.
*/
uint256 public maxStrikePrice;
/**
* @dev Value of the minimum UNIX expiration on ACO token that the pool accept to trade.
*/
uint256 public minExpiration;
/**
* @dev Value of the maximum UNIX expiration on ACO token that the pool accept to trade.
*/
uint256 public maxExpiration;
/**
* @dev True whether the pool accepts CALL options, otherwise the pool accepts only PUT options.
*/
bool public isCall;
/**
* @dev True whether the pool can also buy ACO tokens, otherwise the pool only sells ACO tokens.
*/
bool public canBuy;
/**
* @dev Address of the strategy.
*/
IACOStrategy public strategy;
/**
* @dev Percentage value for the base volatility. (100000 = 100%)
*/
uint256 public baseVolatility;
/**
* @dev Total amount of collateral deposited.
*/
uint256 public collateralDeposited;
/**
* @dev Total amount in strike asset spent buying ACO tokens.
*/
uint256 public strikeAssetSpentBuying;
/**
* @dev Total amount in strike asset earned selling ACO tokens.
*/
uint256 public strikeAssetEarnedSelling;
/**
* @dev Array of ACO tokens currently negotiated.
*/
address[] public acoTokens;
/**
* @dev Mapping for ACO tokens data currently negotiated.
*/
mapping(address => ACOTokenData) public acoTokensData;
/**
* @dev Underlying asset precision. (18 decimals = 1000000000000000000)
*/
uint256 internal underlyingPrecision;
/**
* @dev Strike asset precision. (6 decimals = 1000000)
*/
uint256 internal strikeAssetPrecision;
/**
* @dev Modifier to check if the pool is open to trade.
*/
modifier open() {
require(isStarted() && notFinished(), "ACOPool:: Pool is not open");
_;
}
/**
* @dev Modifier to apply the Chi gas token and save gas.
*/
modifier discountCHI {
uint256 gasStart = gasleft();
_;
uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length;
chiToken.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41947);
}
/**
* @dev Function to initialize the contract.
* It should be called by the ACO pool factory when creating the pool.
* It must be called only once. The first `require` is to guarantee that behavior.
* @param initData The initialize data.
*/
function init(InitData calldata initData) external override {
require(underlying == address(0) && strikeAsset == address(0) && minExpiration == 0, "ACOPool::init: Already initialized");
require(initData.acoFactory.isContract(), "ACOPool:: Invalid ACO Factory");
require(initData.acoFlashExercise.isContract(), "ACOPool:: Invalid ACO flash exercise");
require(initData.chiToken.isContract(), "ACOPool:: Invalid Chi Token");
require(initData.fee <= 12500, "ACOPool:: The maximum fee allowed is 12.5%");
require(initData.poolStart > block.timestamp, "ACOPool:: Invalid pool start");
require(initData.minExpiration > block.timestamp, "ACOPool:: Invalid expiration");
require(initData.minStrikePrice <= initData.maxStrikePrice, "ACOPool:: Invalid strike price range");
require(initData.minStrikePrice > 0, "ACOPool:: Invalid strike price");
require(initData.minExpiration <= initData.maxExpiration, "ACOPool:: Invalid expiration range");
require(initData.underlying != initData.strikeAsset, "ACOPool:: Same assets");
require(ACOAssetHelper._isEther(initData.underlying) || initData.underlying.isContract(), "ACOPool:: Invalid underlying");
require(ACOAssetHelper._isEther(initData.strikeAsset) || initData.strikeAsset.isContract(), "ACOPool:: Invalid strike asset");
super.init();
poolStart = initData.poolStart;
acoFlashExercise = IACOFlashExercise(initData.acoFlashExercise);
acoFactory = IACOFactory(initData.acoFactory);
chiToken = IChiToken(initData.chiToken);
fee = initData.fee;
feeDestination = initData.feeDestination;
underlying = initData.underlying;
strikeAsset = initData.strikeAsset;
minStrikePrice = initData.minStrikePrice;
maxStrikePrice = initData.maxStrikePrice;
minExpiration = initData.minExpiration;
maxExpiration = initData.maxExpiration;
isCall = initData.isCall;
canBuy = initData.canBuy;
address _uniswapRouter = IACOFlashExercise(initData.acoFlashExercise).uniswapRouter();
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
_setStrategy(initData.strategy);
_setBaseVolatility(initData.baseVolatility);
_setAssetsPrecision(initData.underlying, initData.strikeAsset);
_approveAssetsOnRouter(initData.isCall, initData.canBuy, _uniswapRouter, initData.underlying, initData.strikeAsset);
}
receive() external payable {
}
/**
* @dev Function to get the token name.
*/
function name() public view override returns(string memory) {
return _name();
}
/**
* @dev Function to get the token symbol, that it is equal to the name.
*/
function symbol() public view override returns(string memory) {
return _name();
}
/**
* @dev Function to get the token decimals.
*/
function decimals() public view override returns(uint8) {
return 18;
}
/**
* @dev Function to get whether the pool already started trade ACO tokens.
*/
function isStarted() public view returns(bool) {
return block.timestamp >= poolStart;
}
/**
* @dev Function to get whether the pool is not finished.
*/
function notFinished() public view returns(bool) {
return block.timestamp < maxExpiration;
}
/**
* @dev Function to get the number of ACO tokens currently negotiated.
*/
function numberOfACOTokensCurrentlyNegotiated() public override view returns(uint256) {
return acoTokens.length;
}
/**
* @dev Function to get the pool collateral asset.
*/
function collateral() public override view returns(address) {
if (isCall) {
return underlying;
} else {
return strikeAsset;
}
}
/**
* @dev Function to quote an ACO token swap.
* @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token.
* @param acoToken Address of the ACO token.
* @param tokenAmount Amount of ACO tokens to swap.
* @return The swap price, the protocol fee charged on the swap, and the underlying price in strike asset.
*/
function quote(bool isBuying, address acoToken, uint256 tokenAmount) open public override view returns(uint256, uint256, uint256) {
(uint256 swapPrice, uint256 protocolFee, uint256 underlyingPrice,) = _internalQuote(isBuying, acoToken, tokenAmount);
return (swapPrice, protocolFee, underlyingPrice);
}
/**
* @dev Function to set the pool strategy address.
* Only can be called by the ACO pool factory contract.
* @param newStrategy Address of the new strategy.
*/
function setStrategy(address newStrategy) onlyOwner external override {
_setStrategy(newStrategy);
}
/**
* @dev Function to set the pool base volatility percentage. (100000 = 100%)
* Only can be called by the ACO pool factory contract.
* @param newBaseVolatility Value of the new base volatility.
*/
function setBaseVolatility(uint256 newBaseVolatility) onlyOwner external override {
_setBaseVolatility(newBaseVolatility);
}
/**
* @dev Function to deposit on the pool.
* Only can be called when the pool is not started.
* @param collateralAmount Amount of collateral to be deposited.
* @param to Address of the destination of the pool token.
* @return The amount of pool tokens minted.
*/
function deposit(uint256 collateralAmount, address to) public override payable returns(uint256) {
require(!isStarted(), "ACOPool:: Pool already started");
require(collateralAmount > 0, "ACOPool:: Invalid collateral amount");
require(to != address(0) && to != address(this), "ACOPool:: Invalid to");
(uint256 normalizedAmount, uint256 amount) = _getNormalizedDepositAmount(collateralAmount);
ACOAssetHelper._receiveAsset(collateral(), amount);
collateralDeposited = collateralDeposited.add(amount);
_mintAction(to, normalizedAmount);
emit CollateralDeposited(msg.sender, amount);
return normalizedAmount;
}
/**
* @dev Function to swap an ACO token with the pool.
* Only can be called when the pool is opened.
* @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token.
* @param acoToken Address of the ACO token.
* @param tokenAmount Amount of ACO tokens to swap.
* @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase.
* @param to Address of the destination. ACO tokens when is buying or strike asset on a selling.
* @param deadline UNIX deadline for the swap to be executed.
* @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling.
*/
function swap(
bool isBuying,
address acoToken,
uint256 tokenAmount,
uint256 restriction,
address to,
uint256 deadline
) open public override returns(uint256) {
return _swap(isBuying, acoToken, tokenAmount, restriction, to, deadline);
}
/**
* @dev Function to swap an ACO token with the pool and use Chi token to save gas.
* Only can be called when the pool is opened.
* @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token.
* @param acoToken Address of the ACO token.
* @param tokenAmount Amount of ACO tokens to swap.
* @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase.
* @param to Address of the destination. ACO tokens when is buying or strike asset on a selling.
* @param deadline UNIX deadline for the swap to be executed.
* @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling.
*/
function swapWithGasToken(
bool isBuying,
address acoToken,
uint256 tokenAmount,
uint256 restriction,
address to,
uint256 deadline
) open discountCHI public override returns(uint256) {
return _swap(isBuying, acoToken, tokenAmount, restriction, to, deadline);
}
/**
* @dev Function to redeem the collateral and the premium from the pool.
* Only can be called when the pool is finished.
* @return The amount of underlying asset received and the amount of strike asset received.
*/
function redeem() public override returns(uint256, uint256) {
return _redeem(msg.sender);
}
/**
* @dev Function to redeem the collateral and the premium from the pool from an account.
* Only can be called when the pool is finished.
* The allowance must be respected.
* The transaction sender will receive the redeemed assets.
* @param account Address of the account.
* @return The amount of underlying asset received and the amount of strike asset received.
*/
function redeemFrom(address account) public override returns(uint256, uint256) {
return _redeem(account);
}
/**
* @dev Function to redeem the collateral from the ACO tokens negotiated on the pool.
* It redeems the collateral only if the respective ACO token is expired.
*/
function redeemACOTokens() public override {
for (uint256 i = acoTokens.length; i > 0; --i) {
address acoToken = acoTokens[i - 1];
uint256 expiryTime = IACOToken(acoToken).expiryTime();
_redeemACOToken(acoToken, expiryTime);
}
}
/**
* @dev Function to redeem the collateral from an ACO token.
* It redeems the collateral only if the ACO token is expired.
* @param acoToken Address of the ACO token.
*/
function redeemACOToken(address acoToken) public override {
(,uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken);
_redeemACOToken(acoToken, expiryTime);
}
/**
* @dev Function to exercise an ACO token negotiated on the pool.
* Only ITM ACO tokens are exercisable.
* @param acoToken Address of the ACO token.
*/
function exerciseACOToken(address acoToken) public override {
(uint256 strikePrice, uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken);
uint256 exercisableAmount = _getExercisableAmount(acoToken);
require(exercisableAmount > 0, "ACOPool:: Exercise is not available");
address _strikeAsset = strikeAsset;
address _underlying = underlying;
bool _isCall = isCall;
uint256 collateralAmount;
address _collateral;
if (_isCall) {
_collateral = _underlying;
collateralAmount = exercisableAmount;
} else {
_collateral = _strikeAsset;
collateralAmount = IACOToken(acoToken).getCollateralAmount(exercisableAmount);
}
uint256 collateralAvailable = _getPoolBalanceOf(_collateral);
ACOTokenData storage data = acoTokensData[acoToken];
(bool canExercise, uint256 minIntrinsicValue) = strategy.checkExercise(IACOStrategy.CheckExercise(
_underlying,
_strikeAsset,
_isCall,
strikePrice,
expiryTime,
collateralAmount,
collateralAvailable,
data.amountPurchased,
data.amountSold
));
require(canExercise, "ACOPool:: Exercise is not possible");
if (IACOToken(acoToken).allowance(address(this), address(acoFlashExercise)) < exercisableAmount) {
_setAuthorizedSpender(acoToken, address(acoFlashExercise));
}
acoFlashExercise.flashExercise(acoToken, exercisableAmount, minIntrinsicValue, block.timestamp);
uint256 collateralIn = _getPoolBalanceOf(_collateral).sub(collateralAvailable);
emit ACOExercise(acoToken, exercisableAmount, collateralIn);
}
/**
* @dev Function to restore the collateral on the pool by selling the other asset balance.
*/
function restoreCollateral() public override {
address _strikeAsset = strikeAsset;
address _underlying = underlying;
bool _isCall = isCall;
uint256 underlyingBalance = _getPoolBalanceOf(_underlying);
uint256 strikeAssetBalance = _getPoolBalanceOf(_strikeAsset);
uint256 balanceOut;
address assetIn;
address assetOut;
if (_isCall) {
balanceOut = strikeAssetBalance;
assetIn = _underlying;
assetOut = _strikeAsset;
} else {
balanceOut = underlyingBalance;
assetIn = _strikeAsset;
assetOut = _underlying;
}
require(balanceOut > 0, "ACOPool:: No balance");
uint256 acceptablePrice = strategy.getAcceptableUnderlyingPriceToSwapAssets(_underlying, _strikeAsset, false);
uint256 minToReceive;
if (_isCall) {
minToReceive = balanceOut.mul(underlyingPrecision).div(acceptablePrice);
} else {
minToReceive = balanceOut.mul(acceptablePrice).div(underlyingPrecision);
}
_swapAssetsExactAmountOut(assetOut, assetIn, minToReceive, balanceOut);
uint256 collateralIn;
if (_isCall) {
collateralIn = _getPoolBalanceOf(_underlying).sub(underlyingBalance);
} else {
collateralIn = _getPoolBalanceOf(_strikeAsset).sub(strikeAssetBalance);
}
emit RestoreCollateral(balanceOut, collateralIn);
}
/**
* @dev Internal function to swap an ACO token with the pool.
* @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying.
* @param acoToken Address of the ACO token.
* @param tokenAmount Amount of ACO tokens to swap.
* @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase.
* @param to Address of the destination. ACO tokens when is buying or strike asset on a selling.
* @param deadline UNIX deadline for the swap to be executed.
* @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling.
*/
function _swap(
bool isPoolSelling,
address acoToken,
uint256 tokenAmount,
uint256 restriction,
address to,
uint256 deadline
) internal returns(uint256) {
require(block.timestamp <= deadline, "ACOPool:: Swap deadline");
require(to != address(0) && to != acoToken && to != address(this), "ACOPool:: Invalid destination");
(uint256 swapPrice, uint256 protocolFee, uint256 underlyingPrice, uint256 collateralAmount) = _internalQuote(isPoolSelling, acoToken, tokenAmount);
uint256 amount;
if (isPoolSelling) {
amount = _internalSelling(to, acoToken, collateralAmount, tokenAmount, restriction, swapPrice, protocolFee);
} else {
amount = _internalBuying(to, acoToken, tokenAmount, restriction, swapPrice, protocolFee);
}
if (protocolFee > 0) {
ACOAssetHelper._transferAsset(strikeAsset, feeDestination, protocolFee);
}
emit Swap(isPoolSelling, msg.sender, acoToken, tokenAmount, swapPrice, protocolFee, underlyingPrice);
return amount;
}
/**
* @dev Internal function to quote an ACO token price.
* @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying.
* @param acoToken Address of the ACO token.
* @param tokenAmount Amount of ACO tokens to swap.
* @return The quote price, the protocol fee charged, the underlying price, and the collateral amount.
*/
function _internalQuote(bool isPoolSelling, address acoToken, uint256 tokenAmount) internal view returns(uint256, uint256, uint256, uint256) {
require(isPoolSelling || canBuy, "ACOPool:: The pool only sell");
require(tokenAmount > 0, "ACOPool:: Invalid token amount");
(uint256 strikePrice, uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken);
require(expiryTime > block.timestamp, "ACOPool:: ACO token expired");
(uint256 collateralAmount, uint256 collateralAvailable) = _getSizeData(isPoolSelling, acoToken, tokenAmount);
(uint256 price, uint256 underlyingPrice,) = _strategyQuote(acoToken, isPoolSelling, strikePrice, expiryTime, collateralAmount, collateralAvailable);
price = price.mul(tokenAmount).div(underlyingPrecision);
uint256 protocolFee = 0;
if (fee > 0) {
protocolFee = price.mul(fee).div(100000);
if (isPoolSelling) {
price = price.add(protocolFee);
} else {
price = price.sub(protocolFee);
}
}
require(price > 0, "ACOPool:: Invalid quote");
return (price, protocolFee, underlyingPrice, collateralAmount);
}
/**
* @dev Internal function to the size data for a quote.
* @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying.
* @param acoToken Address of the ACO token.
* @param tokenAmount Amount of ACO tokens to swap.
* @return The collateral amount and the collateral available on the pool.
*/
function _getSizeData(bool isPoolSelling, address acoToken, uint256 tokenAmount) internal view returns(uint256, uint256) {
uint256 collateralAmount;
uint256 collateralAvailable;
if (isCall) {
collateralAvailable = _getPoolBalanceOf(underlying);
collateralAmount = tokenAmount;
} else {
collateralAvailable = _getPoolBalanceOf(strikeAsset);
collateralAmount = IACOToken(acoToken).getCollateralAmount(tokenAmount);
require(collateralAmount > 0, "ACOPool:: Token amount is too small");
}
require(!isPoolSelling || collateralAmount <= collateralAvailable, "ACOPool:: Insufficient liquidity");
return (collateralAmount, collateralAvailable);
}
/**
* @dev Internal function to quote on the strategy contract.
* @param acoToken Address of the ACO token.
* @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying.
* @param strikePrice ACO token strike price.
* @param expiryTime ACO token expiry time on UNIX.
* @param collateralAmount Amount of collateral for the order size.
* @param collateralAvailable Amount of collateral available on the pool.
* @return The quote price, the underlying price and the volatility.
*/
function _strategyQuote(
address acoToken,
bool isPoolSelling,
uint256 strikePrice,
uint256 expiryTime,
uint256 collateralAmount,
uint256 collateralAvailable
) internal view returns(uint256, uint256, uint256) {
ACOTokenData storage data = acoTokensData[acoToken];
return strategy.quote(IACOStrategy.OptionQuote(
isPoolSelling,
underlying,
strikeAsset,
isCall,
strikePrice,
expiryTime,
baseVolatility,
collateralAmount,
collateralAvailable,
collateralDeposited,
strikeAssetEarnedSelling,
strikeAssetSpentBuying,
data.amountPurchased,
data.amountSold
));
}
/**
* @dev Internal function to sell ACO tokens.
* @param to Address of the destination of the ACO tokens.
* @param acoToken Address of the ACO token.
* @param collateralAmount Order collateral amount.
* @param tokenAmount Order token amount.
* @param maxPayment Maximum value to be paid for the ACO tokens.
* @param swapPrice The swap price quoted.
* @param protocolFee The protocol fee amount.
* @return The ACO token amount sold.
*/
function _internalSelling(
address to,
address acoToken,
uint256 collateralAmount,
uint256 tokenAmount,
uint256 maxPayment,
uint256 swapPrice,
uint256 protocolFee
) internal returns(uint256) {
require(swapPrice <= maxPayment, "ACOPool:: Swap restriction");
ACOAssetHelper._callTransferFromERC20(strikeAsset, msg.sender, address(this), swapPrice);
uint256 acoBalance = _getPoolBalanceOf(acoToken);
ACOTokenData storage acoTokenData = acoTokensData[acoToken];
uint256 _amountSold = acoTokenData.amountSold;
if (_amountSold == 0 && acoTokenData.amountPurchased == 0) {
acoTokenData.index = acoTokens.length;
acoTokens.push(acoToken);
}
if (tokenAmount > acoBalance) {
tokenAmount = acoBalance;
if (acoBalance > 0) {
collateralAmount = IACOToken(acoToken).getCollateralAmount(tokenAmount.sub(acoBalance));
}
if (collateralAmount > 0) {
address _collateral = collateral();
if (ACOAssetHelper._isEther(_collateral)) {
tokenAmount = tokenAmount.add(IACOToken(acoToken).mintPayable{value: collateralAmount}());
} else {
if (_amountSold == 0) {
_setAuthorizedSpender(_collateral, acoToken);
}
tokenAmount = tokenAmount.add(IACOToken(acoToken).mint(collateralAmount));
}
}
}
acoTokenData.amountSold = tokenAmount.add(_amountSold);
strikeAssetEarnedSelling = swapPrice.sub(protocolFee).add(strikeAssetEarnedSelling);
ACOAssetHelper._callTransferERC20(acoToken, to, tokenAmount);
return tokenAmount;
}
/**
* @dev Internal function to buy ACO tokens.
* @param to Address of the destination of the premium.
* @param acoToken Address of the ACO token.
* @param tokenAmount Order token amount.
* @param minToReceive Minimum value to be received for the ACO tokens.
* @param swapPrice The swap price quoted.
* @param protocolFee The protocol fee amount.
* @return The premium amount transferred.
*/
function _internalBuying(
address to,
address acoToken,
uint256 tokenAmount,
uint256 minToReceive,
uint256 swapPrice,
uint256 protocolFee
) internal returns(uint256) {
require(swapPrice >= minToReceive, "ACOPool:: Swap restriction");
uint256 requiredStrikeAsset = swapPrice.add(protocolFee);
if (isCall) {
_getStrikeAssetAmount(requiredStrikeAsset);
}
ACOAssetHelper._callTransferFromERC20(acoToken, msg.sender, address(this), tokenAmount);
ACOTokenData storage acoTokenData = acoTokensData[acoToken];
uint256 _amountPurchased = acoTokenData.amountPurchased;
if (_amountPurchased == 0 && acoTokenData.amountSold == 0) {
acoTokenData.index = acoTokens.length;
acoTokens.push(acoToken);
}
acoTokenData.amountPurchased = tokenAmount.add(_amountPurchased);
strikeAssetSpentBuying = requiredStrikeAsset.add(strikeAssetSpentBuying);
ACOAssetHelper._transferAsset(strikeAsset, to, swapPrice);
return swapPrice;
}
/**
* @dev Internal function to get the normalized deposit amount.
* The pool token has always with 18 decimals.
* @param collateralAmount Amount of collateral to be deposited.
* @return The normalized token amount and the collateral amount.
*/
function _getNormalizedDepositAmount(uint256 collateralAmount) internal view returns(uint256, uint256) {
uint256 basePrecision = isCall ? underlyingPrecision : strikeAssetPrecision;
uint256 normalizedAmount;
if (basePrecision > POOL_PRECISION) {
uint256 adjust = basePrecision.div(POOL_PRECISION);
normalizedAmount = collateralAmount.div(adjust);
collateralAmount = normalizedAmount.mul(adjust);
} else if (basePrecision < POOL_PRECISION) {
normalizedAmount = collateralAmount.mul(POOL_PRECISION.div(basePrecision));
} else {
normalizedAmount = collateralAmount;
}
require(normalizedAmount > 0, "ACOPool:: Invalid collateral amount");
return (normalizedAmount, collateralAmount);
}
/**
* @dev Internal function to get an amount of strike asset for the pool.
* The pool swaps the collateral for it if necessary.
* @param strikeAssetAmount Amount of strike asset required.
*/
function _getStrikeAssetAmount(uint256 strikeAssetAmount) internal {
address _strikeAsset = strikeAsset;
uint256 balance = _getPoolBalanceOf(_strikeAsset);
if (balance < strikeAssetAmount) {
uint256 amountToPurchase = strikeAssetAmount.sub(balance);
address _underlying = underlying;
uint256 acceptablePrice = strategy.getAcceptableUnderlyingPriceToSwapAssets(_underlying, _strikeAsset, true);
uint256 maxPayment = amountToPurchase.mul(underlyingPrecision).div(acceptablePrice);
_swapAssetsExactAmountIn(_underlying, _strikeAsset, amountToPurchase, maxPayment);
}
}
/**
* @dev Internal function to redeem the collateral from an ACO token.
* It redeems the collateral only if the ACO token is expired.
* @param acoToken Address of the ACO token.
* @param expiryTime ACO token expiry time in UNIX.
*/
function _redeemACOToken(address acoToken, uint256 expiryTime) internal {
if (expiryTime <= block.timestamp) {
uint256 collateralIn = 0;
if (IACOToken(acoToken).currentCollateralizedTokens(address(this)) > 0) {
collateralIn = IACOToken(acoToken).redeem();
}
ACOTokenData storage data = acoTokensData[acoToken];
uint256 lastIndex = acoTokens.length - 1;
if (lastIndex != data.index) {
address last = acoTokens[lastIndex];
acoTokensData[last].index = data.index;
acoTokens[data.index] = last;
}
emit ACORedeem(acoToken, collateralIn, data.amountSold, data.amountPurchased);
acoTokens.pop();
delete acoTokensData[acoToken];
}
}
/**
* @dev Internal function to redeem the collateral and the premium from the pool from an account.
* @param account Address of the account.
* @return The amount of underlying asset received and the amount of strike asset received.
*/
function _redeem(address account) internal returns(uint256, uint256) {
uint256 share = balanceOf(account);
require(share > 0, "ACOPool:: Account with no share");
require(!notFinished(), "ACOPool:: Pool is not finished");
redeemACOTokens();
uint256 _totalSupply = totalSupply();
uint256 underlyingBalance = share.mul(_getPoolBalanceOf(underlying)).div(_totalSupply);
uint256 strikeAssetBalance = share.mul(_getPoolBalanceOf(strikeAsset)).div(_totalSupply);
_callBurn(account, share);
if (underlyingBalance > 0) {
ACOAssetHelper._transferAsset(underlying, msg.sender, underlyingBalance);
}
if (strikeAssetBalance > 0) {
ACOAssetHelper._transferAsset(strikeAsset, msg.sender, strikeAssetBalance);
}
emit Redeem(msg.sender, underlyingBalance, strikeAssetBalance);
return (underlyingBalance, strikeAssetBalance);
}
/**
* @dev Internal function to burn pool tokens.
* @param account Address of the account.
* @param tokenAmount Amount of pool tokens to be burned.
*/
function _callBurn(address account, uint256 tokenAmount) internal {
if (account == msg.sender) {
super._burnAction(account, tokenAmount);
} else {
super._burnFrom(account, tokenAmount);
}
}
/**
* @dev Internal function to swap assets on the Uniswap V2 with an exact amount of an asset to be sold.
* @param assetOut Address of the asset to be sold.
* @param assetIn Address of the asset to be purchased.
* @param minAmountIn Minimum amount to be received.
* @param amountOut The exact amount to be sold.
*/
function _swapAssetsExactAmountOut(address assetOut, address assetIn, uint256 minAmountIn, uint256 amountOut) internal {
address[] memory path = new address[](2);
if (ACOAssetHelper._isEther(assetOut)) {
path[0] = acoFlashExercise.weth();
path[1] = assetIn;
uniswapRouter.swapExactETHForTokens{value: amountOut}(minAmountIn, path, address(this), block.timestamp);
} else if (ACOAssetHelper._isEther(assetIn)) {
path[0] = assetOut;
path[1] = acoFlashExercise.weth();
uniswapRouter.swapExactTokensForETH(amountOut, minAmountIn, path, address(this), block.timestamp);
} else {
path[0] = assetOut;
path[1] = assetIn;
uniswapRouter.swapExactTokensForTokens(amountOut, minAmountIn, path, address(this), block.timestamp);
}
}
/**
* @dev Internal function to swap assets on the Uniswap V2 with an exact amount of an asset to be purchased.
* @param assetOut Address of the asset to be sold.
* @param assetIn Address of the asset to be purchased.
* @param amountIn The exact amount to be purchased.
* @param maxAmountOut Maximum amount to be paid.
*/
function _swapAssetsExactAmountIn(address assetOut, address assetIn, uint256 amountIn, uint256 maxAmountOut) internal {
address[] memory path = new address[](2);
if (ACOAssetHelper._isEther(assetOut)) {
path[0] = acoFlashExercise.weth();
path[1] = assetIn;
uniswapRouter.swapETHForExactTokens{value: maxAmountOut}(amountIn, path, address(this), block.timestamp);
} else if (ACOAssetHelper._isEther(assetIn)) {
path[0] = assetOut;
path[1] = acoFlashExercise.weth();
uniswapRouter.swapTokensForExactETH(amountIn, maxAmountOut, path, address(this), block.timestamp);
} else {
path[0] = assetOut;
path[1] = assetIn;
uniswapRouter.swapTokensForExactTokens(amountIn, maxAmountOut, path, address(this), block.timestamp);
}
}
/**
* @dev Internal function to set the strategy address.
* @param newStrategy Address of the new strategy.
*/
function _setStrategy(address newStrategy) internal {
require(newStrategy.isContract(), "ACOPool:: Invalid strategy");
emit SetStrategy(address(strategy), newStrategy);
strategy = IACOStrategy(newStrategy);
}
/**
* @dev Internal function to set the base volatility percentage. (100000 = 100%)
* @param newBaseVolatility Value of the new base volatility.
*/
function _setBaseVolatility(uint256 newBaseVolatility) internal {
require(newBaseVolatility > 0, "ACOPool:: Invalid base volatility");
emit SetBaseVolatility(baseVolatility, newBaseVolatility);
baseVolatility = newBaseVolatility;
}
/**
* @dev Internal function to set the pool assets precisions.
* @param _underlying Address of the underlying asset.
* @param _strikeAsset Address of the strike asset.
*/
function _setAssetsPrecision(address _underlying, address _strikeAsset) internal {
underlyingPrecision = 10 ** uint256(ACOAssetHelper._getAssetDecimals(_underlying));
strikeAssetPrecision = 10 ** uint256(ACOAssetHelper._getAssetDecimals(_strikeAsset));
}
/**
* @dev Internal function to infinite authorize the pool assets on the Uniswap V2 router.
* @param _isCall True whether it is a CALL option, otherwise it is PUT.
* @param _canBuy True whether the pool can also buy ACO tokens, otherwise it only sells.
* @param _uniswapRouter Address of the Uniswap V2 router.
* @param _underlying Address of the underlying asset.
* @param _strikeAsset Address of the strike asset.
*/
function _approveAssetsOnRouter(
bool _isCall,
bool _canBuy,
address _uniswapRouter,
address _underlying,
address _strikeAsset
) internal {
if (_isCall) {
if (!ACOAssetHelper._isEther(_strikeAsset)) {
_setAuthorizedSpender(_strikeAsset, _uniswapRouter);
}
if (_canBuy && !ACOAssetHelper._isEther(_underlying)) {
_setAuthorizedSpender(_underlying, _uniswapRouter);
}
} else if (!ACOAssetHelper._isEther(_underlying)) {
_setAuthorizedSpender(_underlying, _uniswapRouter);
}
}
/**
* @dev Internal function to infinite authorize a spender on an asset.
* @param asset Address of the asset.
* @param spender Address of the spender to be authorized.
*/
function _setAuthorizedSpender(address asset, address spender) internal {
ACOAssetHelper._callApproveERC20(asset, spender, MAX_UINT);
}
/**
* @dev Internal function to get the pool balance of an asset.
* @param asset Address of the asset.
* @return The pool balance.
*/
function _getPoolBalanceOf(address asset) internal view returns(uint256) {
return ACOAssetHelper._getAssetBalanceOf(asset, address(this));
}
/**
* @dev Internal function to get the exercible amount of an ACO token.
* @param acoToken Address of the ACO token.
* @return The exercisable amount.
*/
function _getExercisableAmount(address acoToken) internal view returns(uint256) {
uint256 balance = _getPoolBalanceOf(acoToken);
if (balance > 0) {
uint256 collaterized = IACOToken(acoToken).currentCollateralizedTokens(address(this));
if (balance > collaterized) {
return balance.sub(collaterized);
}
}
return 0;
}
/**
* @dev Internal function to get an accepted ACO token by the pool.
* @param acoToken Address of the ACO token.
* @return The ACO token strike price, and the ACO token expiration.
*/
function _getValidACOTokenStrikePriceAndExpiration(address acoToken) internal view returns(uint256, uint256) {
(address _underlying, address _strikeAsset, bool _isCall, uint256 _strikePrice, uint256 _expiryTime) = acoFactory.acoTokenData(acoToken);
require(
_underlying == underlying &&
_strikeAsset == strikeAsset &&
_isCall == isCall &&
_strikePrice >= minStrikePrice &&
_strikePrice <= maxStrikePrice &&
_expiryTime >= minExpiration &&
_expiryTime <= maxExpiration,
"ACOPool:: Invalid ACO Token"
);
return (_strikePrice, _expiryTime);
}
/**
* @dev Internal function to get the token name.
* The token name is assembled with the token data:
* ACO POOL UNDERLYING_SYMBOL-STRIKE_ASSET_SYMBOL-TYPE-{ONLY_SELL}-MIN_STRIKE_PRICE-MAX_STRIKE_PRICE-MIN_EXPIRATION-MAX_EXPIRATION
* @return The token name.
*/
function _name() internal view returns(string memory) {
uint8 strikeDecimals = ACOAssetHelper._getAssetDecimals(strikeAsset);
string memory strikePriceFormatted;
if (minStrikePrice != maxStrikePrice) {
strikePriceFormatted = string(abi.encodePacked(ACONameFormatter.formatNumber(minStrikePrice, strikeDecimals), "-", ACONameFormatter.formatNumber(maxStrikePrice, strikeDecimals)));
} else {
strikePriceFormatted = ACONameFormatter.formatNumber(minStrikePrice, strikeDecimals);
}
string memory dateFormatted;
if (minExpiration != maxExpiration) {
dateFormatted = string(abi.encodePacked(ACONameFormatter.formatTime(minExpiration), "-", ACONameFormatter.formatTime(maxExpiration)));
} else {
dateFormatted = ACONameFormatter.formatTime(minExpiration);
}
return string(abi.encodePacked(
"ACO POOL ",
ACOAssetHelper._getAssetSymbol(underlying),
"-",
ACOAssetHelper._getAssetSymbol(strikeAsset),
"-",
ACONameFormatter.formatType(isCall),
(canBuy ? "" : "-SELL"),
"-",
strikePriceFormatted,
"-",
dateFormatted
));
}
} | * @dev Internal function to swap assets on the Uniswap V2 with an exact amount of an asset to be sold. @param assetOut Address of the asset to be sold. @param assetIn Address of the asset to be purchased. @param minAmountIn Minimum amount to be received. @param amountOut The exact amount to be sold./ | function _swapAssetsExactAmountOut(address assetOut, address assetIn, uint256 minAmountIn, uint256 amountOut) internal {
address[] memory path = new address[](2);
if (ACOAssetHelper._isEther(assetOut)) {
path[0] = acoFlashExercise.weth();
path[1] = assetIn;
path[0] = assetOut;
path[1] = acoFlashExercise.weth();
uniswapRouter.swapExactTokensForETH(amountOut, minAmountIn, path, address(this), block.timestamp);
path[0] = assetOut;
path[1] = assetIn;
uniswapRouter.swapExactTokensForTokens(amountOut, minAmountIn, path, address(this), block.timestamp);
}
}
| 48,903 | [
1,
3061,
445,
358,
7720,
7176,
603,
326,
1351,
291,
91,
438,
776,
22,
598,
392,
5565,
3844,
434,
392,
3310,
358,
506,
272,
1673,
18,
225,
3310,
1182,
5267,
434,
326,
3310,
358,
506,
272,
1673,
18,
225,
3310,
382,
5267,
434,
326,
3310,
358,
506,
5405,
343,
8905,
18,
225,
1131,
6275,
382,
23456,
3844,
358,
506,
5079,
18,
225,
3844,
1182,
1021,
5565,
3844,
358,
506,
272,
1673,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
389,
22270,
10726,
14332,
6275,
1182,
12,
2867,
3310,
1182,
16,
1758,
3310,
382,
16,
2254,
5034,
1131,
6275,
382,
16,
2254,
5034,
3844,
1182,
13,
2713,
288,
203,
3639,
1758,
8526,
3778,
589,
273,
394,
1758,
8526,
12,
22,
1769,
203,
3639,
309,
261,
2226,
51,
6672,
2276,
6315,
291,
41,
1136,
12,
9406,
1182,
3719,
288,
203,
5411,
589,
63,
20,
65,
273,
1721,
83,
11353,
424,
20603,
18,
91,
546,
5621,
203,
5411,
589,
63,
21,
65,
273,
3310,
382,
31,
203,
5411,
589,
63,
20,
65,
273,
3310,
1182,
31,
203,
5411,
589,
63,
21,
65,
273,
1721,
83,
11353,
424,
20603,
18,
91,
546,
5621,
203,
5411,
640,
291,
91,
438,
8259,
18,
22270,
14332,
5157,
1290,
1584,
44,
12,
8949,
1182,
16,
1131,
6275,
382,
16,
589,
16,
1758,
12,
2211,
3631,
1203,
18,
5508,
1769,
203,
5411,
589,
63,
20,
65,
273,
3310,
1182,
31,
203,
5411,
589,
63,
21,
65,
273,
3310,
382,
31,
203,
5411,
640,
291,
91,
438,
8259,
18,
22270,
14332,
5157,
1290,
5157,
12,
8949,
1182,
16,
1131,
6275,
382,
16,
589,
16,
1758,
12,
2211,
3631,
1203,
18,
5508,
1769,
203,
3639,
289,
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
]
|
// LC->24.10.2015
tree_scorers ОдушОбъект
tree_scorer ОдушОбъект language=Russian
{
if context { местоим_сущ:кто{} }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { местоим_сущ:кто-нибудь{} }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { местоим_сущ:кто-то{} }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { местоим_сущ:кто-либо{} }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { существительное:*{ одуш:одуш } }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { местоимение:я{ род:муж } }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { местоимение:я{ род:жен } }
then 1
}
// друзья должны были дождаться нас у леса
// ^^^
tree_scorer ОдушОбъект language=Russian
{
if context { местоимение:я{ лицо:1 } }
then 1
}
// Я дождусь вас
// ^^^
tree_scorer ОдушОбъект language=Russian
{
if context { местоимение:я{ лицо:2 } }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { 'себе' }
then 1
}
tree_scorers НеодушОбъект
tree_scorer НеодушОбъект language=Russian
{
if context { существительное:*{ одуш:неодуш } }
then 1
}
tree_scorer НеодушОбъект language=Russian
{
if context { местоим_сущ:что-то{} }
then 1
}
tree_scorer НеодушОбъект language=Russian
{
if context { местоимение:я{ род:ср } }
then 1
}
tree_scorer НеодушОбъект language=Russian
{
if context { местоим_сущ:что{} }
then 1
}
tree_scorer НеодушОбъект language=Russian
{
if context { местоим_сущ:что-нибудь{} }
then 1
}
tree_scorer НеодушОбъект language=Russian
{
if context { местоим_сущ:что-либо{} }
then 1
}
// ------------------------------------
/*
function int CheckVerbSubjectConcord( tree v, tree sbj )
{
int res_score=0;
// Для безличных глаголов проверять не надо.
if( eq( wordform_class(v),ГЛАГОЛ) )
then
{
int sbj_number = wordform_get_coord( sbj, ЧИСЛО );
if( eq(sbj_number,-1) )
then
{
// Подлежащим может оказаться часть речи без категории числа.
// У нас есть кое-что общее.
// ^^^^^^^
if( eq( wordform_class( sbj ), МЕСТОИМ_СУЩ ) )
then sbj_number = ЧИСЛО:ЕД;
else if( eq( wordform_class( sbj ), ИНФИНИТИВ ) )
then sbj_number = ЧИСЛО:ЕД;
}
int v_number = wordform_get_coord( v, ЧИСЛО );
// согласование по числу выполняется в любом времени
if( neq( sbj_number, v_number ) )
then res_score=-10; // рассогласование по числу
else
{
int v_tense = wordform_get_coord( v, ВРЕМЯ );
if( eq( v_tense, ВРЕМЯ:ПРОШЕДШЕЕ ) )
then
{
if( eq( v_number, ЧИСЛО:ЕД ) )
then
{
// В прошедшем времени надо сопоставить род.
// Если подлежащее - местоимение Я в первом или втором лице, то род
// проверять не надо:
// А я и не слышала.
// ^^^ ^^^^^^^
if( log_and(
eq( wordform_class(sbj), МЕСТОИМЕНИЕ ),
one_of( wordform_get_coord(sbj,ЛИЦО), ЛИЦО:1, ЛИЦО:2 )
) )
then
{
// nothing to check
}
else
{
int sbj_gender = wordform_get_coord( sbj, РОД );
int v_gender = wordform_get_coord( v, РОД );
if( neq( sbj_gender, v_gender ) )
then res_score=-10; // рассогласование по роду
}
}
}
else
{
// в настоящем и будущем времени надо сопоставить число и лицо
// особый случай - глагол ЕСТЬ (форма глагола БЫТЬ настоящего времени),
// она не имеет признака лица.
int sbj_person = wordform_get_coord( sbj, ЛИЦО );
if( eq( sbj_person, -1 ) )
then sbj_person=ЛИЦО:3;
if( log_not( eqi( wordform_lexem(v), 'есть' ) ) )
then
{
int v_person = wordform_get_coord( v, ЛИЦО );
if( neq( sbj_person, v_person ) )
then res_score=-10; // рассогласование по лицу
}
}
}
}
return res_score;
}
// Обычный предикат с глаголом в личной форме:
// Я буду читать сказку
// ^^^^^^^^^^^^^
//
// Безличная конструкция:
// от этого мне было жаль отказываться
// ^^^ ^^^^ ^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { инфинитив:*{}.{ v=<LEFT_AUX_VERB>глагол:*{} sbj=<SUBJECT>*:*{} } }
then CheckVerbSubjectConcord(v,sbj)
}
// Суд вынес решение
// ^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { v=глагол:*{}.sbj=<SUBJECT>*:*{} }
then CheckVerbSubjectConcord(v,sbj)
}
*/
// ------------------------------------
// В предложении БЕЖАТЬ НА УРОК понижаем достоверность распознавания УРОК как формы слова УРКА,
// предпочитая неодушевленные объекты.
tree_scorer language=Russian
{
if context { rus_verbs:бежать{}.предлог:на{}.ОдушОбъект }
then -1
}
// пойти на урок
// ^^^^^
tree_scorer language=Russian
{
if context { rus_verbs:пойти{}.предлог:на{}.ОдушОбъект }
then -1
}
// Стали слышны крики играющих детей
// ^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:*{}.<OBJECT>существительное:сталь{падеж:дат} }
then -10
}
// давно хотел взять его рабочий телефон.
// --> неодушевленные обычно не хотят
tree_scorer language=Russian { if context { rus_verbs:хотеть{}.<SUBJECT>НеодушОбъект } then -2 }
tree_scorer language=Russian { if context { rus_verbs:захотеть{}.<SUBJECT>НеодушОбъект } then -2 }
//+tree_scorer language=Russian { if context { rus_verbs:перехотеть{}.<SUBJECT>НеодушОбъект } then -2 }
// ------------------------------------------------------
// Чтобы подавить связывание глагола с предложным паттерном в конструкции:
// завтракать яичницей с беконом
// ^^^^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:завтракать{}.предлог:с{}.существительное:*{ одуш:неодуш <в_класс>существительное:еда{} } }
then -10
}
tree_scorer language=Russian
{
if context { существительное:*{ одуш:неодуш <в_класс>существительное:еда{} }
.предлог:с{}.существительное:*{ одуш:неодуш <в_класс>существительное:еда{} падеж:твор }
}
then 2
}
// Обычно ЯВЛЯТЬСЯ можно кому-то, а не чему-то
// Цена является денежным выражением стоимости.
// ^^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:являться{}.<OBJECT>существительное:*{ падеж:дат одуш:неодуш } }
then -10
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:явиться{}.<OBJECT>существительное:*{ падеж:дат одуш:неодуш } }
then -10
}
// обрушивать на головы врагов
// ^^^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обрушивать{}.<OBJECT>существительное:*{ одуш:одуш падеж:вин} }
then -10
}
// Мы подали им руку помощи.
// ^^^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подать{}.<OBJECT>местоимение:я{ падеж:дат } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подать{}.<OBJECT>существительное:*{ одуш:одуш падеж:дат } }
then 2
}
// Белки прячутся в дупле
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:прятаться{}.<SUBJECT>ОдушОбъект }
then 2
}
// им пришлось идти боком.
// ^^ ^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:пришлось{}.<SUBJECT>*:*{ падеж:дат } }
then 2
}
// Основным доводом явилось беспокойство за сохранение здоровой экологической обстановки.
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { существительное:беспокойство{}.предлог:за{}.*:*{падеж:вин} }
then 2
}
// Команды-победительницы в каждой номинации получили сертификаты на спутниковые тарелки.
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { существительное:сертификат{}.предлог:на{}.*:*{падеж:вин} }
then 2
}
// Поводом для раскрытия банковской тайны могут стать подозрения в нарушении налогового законодательства
// ^^^^^^^^^^^...
tree_scorer language=Russian
{
if context { существительное:повод{}.предлог:для{} }
then 2
}
// - Вы знали, что перевоплощаться в существа другого биологического вида запрещено сроком на шесть месяцев?
// ^^^^^^^^^
tree_scorer language=Russian
{
if context { существительное:срок{падеж:твор}.предлог:на{} }
then 5
}
// различные страны продолжают осуществлять политику по укреплению своих позиций на Южном Кавказе
// ^^^^^^^^^^^...
tree_scorer language=Russian
{
if context { существительное:политика{}.предлог:по{} }
then 2
}
// Она не могла оторвать взгляда от их грубой подошвы и толстых ниток, прошивающих ботинки по краям.
// ^^^^^^^^ ^^...
tree_scorer language=Russian
{
if context { rus_verbs:оторвать{}.предлог:от{} }
then 2
}
// Предварительное расследование пока исключает вмешательство членов экипажа в работу системы пожаротушения.
tree_scorer language=Russian
{
if context { существительное:вмешательство{}.предлог:в{}.*:*{падеж:вин} }
then 2
}
// Европейский союз готов присоединиться к украинско-российским переговорам по пересмотру цены на газ
// ^^^^^^^^^^^^^^...
tree_scorer language=Russian
{
if context { существительное:переговоры{}.предлог:по{}.*:*{падеж:дат} }
then 2
}
// Ведь и в Мадриде, и в Барселоне начиналось именно с шумихи вокруг их гастрольной поездки...
// ^^^^^^^^^^^^^^...
tree_scorer language=Russian
{
if context { существительное:шумиха{}.предлог:вокруг{} }
then 2
}
// проводили мероприятие по выявлению лиц , занимающихся изготовлением контрафактных лекарств
// ^^^^^^^^^^^^^^^^...
tree_scorer language=Russian
{
if context { существительное:мероприятие{}.предлог:по{}.*:*{падеж:дат} }
then 2
}
// Ведь не была же она настолько наивна, чтобы верить во всю эту чушь насчет надежной мужской руки
// ^^^^^^^^^^^...
tree_scorer language=Russian
{
if context { существительное:чушь{}.предлог:насчет{} }
then 2
}
// Они занимались распространением наркотиков среди посетителей этого увеселительного заведения.
// ^^^^^^^^^^^^^^^^ ^^^^^
tree_scorer language=Russian
{
if context { существительное:распространение{}.предлог:среди{}.*:*{падеж:род} }
then 2
}
// Этот фильм посвящен попытке человека освободиться от своего прошлого, начать новую жизнь
// ^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { rus_verbs:освободиться{}.предлог:от{}.*:*{падеж:род} }
then 2
}
// старик прав : все имеет свою цену.
// ^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:правый{ краткий число:ед род:муж }.<SUBJECT>*:*{ падеж:им род:муж число:ед } }
then 2
}
// тем временем надо приготовить лодки.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приготовить{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// Мы выбрали его секретарём нашей организации.
// ^^^^^^^ ^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:выбрать{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>существительное:*{ падеж:твор }
} }
then 3
}
// При жизни его не ценили.
// ^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ценить{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// разгрести в задачах залежи
// ^^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:разгрести{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } }
then 2
}
// император осторожно коснулся пальцами белой перчатки.
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:коснуться{}.{
<OBJECT>*:*{ падеж:твор }
<OBJECT>*:*{ падеж:род }
} }
then 4
}
// именно поэтому она собиралась предложить им очень простой выбор.
// ^^^^^^^^^^ ^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:предложить{}.{
<OBJECT>*:*{ падеж:дат }
<OBJECT>*:*{ падеж:вин }
} }
then 1
}
// девушка смутно ощущала тепло.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ощущать{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// Томас внимательно рассматривал дома.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:рассматривать{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// Ричард обвел глазами окрестности.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обвести{}.{
<OBJECT>*:*{ падеж:твор }
<OBJECT>*:*{ падеж:вин }
} }
then 4
}
// император осторожно коснулся пальцами белой перчатки.
// ^^^^^^^^ ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:коснуться{}.*:*{ падеж:род } }
then 1
}
// собирать щеткой крошки со стола
// ^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:собирать{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// Глагол ТРУБИТЬ обычно не присоединяет одушевленное прямое дополнение:
// трубить о поимке разбойников
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:трубить{}.<OBJECT>*:*{ одуш:одуш } }
then -10
}
// Глагол СЛАГАТЬ обычно не присоединяет одушевленное прямое дополнение:
// слагать о подвигах викингов
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:слагать{}.<OBJECT>*:*{ одуш:одуш } }
then -10
}
// семья арендовала домик у владельца
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:арендовать{}.предлог:у{}.*:*{ падеж:род одуш:одуш } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:арендовать{}.предлог:у{}.местоимение:*{ падеж:род } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:арендовать{}.предлог:у{}.местоим_сущ:*{ падеж:род } }
then 2
}
// укрыться от маньяка в доме
// ^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:укрыться{}.предлог:в{}.*:*{ падеж:предл } }
then 2
}
// уединяться с подругой в доме
// ^^^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:уединяться{}.предлог:в{}.*:*{ падеж:предл } }
then 2
}
// Дни стали короче.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:стать{}.прилагательное:*{ степень:сравн } }
then 2
}
// Чтобы устранить вариант с творительным падежом:
// причинить животным страдания
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:причинить{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:дат }
} }
then 4
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:причинять{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:дат }
} }
then 4
}
// запах реки сделался сильнее.
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сделаться{}.прилагательное:*{ степень:сравн } }
then 2
}
// У вас есть чистый лист бумаги и конверт?
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{ время:настоящее }.предлог:у{}.*:*{ падеж:род } }
then 2
}
// знакомая опасность казалась страшнее.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:казаться{}.прилагательное:*{ степень:сравн } }
then 2
}
// день будет становиться короче и немного тоскливее
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:становиться{}.прилагательное:*{ степень:сравн } }
then 2
}
// Снимаем омонимию кратких форм ЗАМЕТНЫЙ-ЗАМЕТЕННЫЙ:
// Юпитер заметен невооруженным взглядом
// ^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:заметный{}.<OBJECT>'взглядом' }
then 2
}
/*
// Студентка села за стол и начала читать журнал.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:начать{}.инфинитив:*{ вид:несоверш } }
then 2
}
*/
// Село должно отпраздновать окончание страды
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:должный{ КРАТКИЙ }.инфинитив:*{} }
then 2
}
// ПОРА с инфинитивом обычно является безличным глаголом:
// пора учиться мыслить шире.
tree_scorer ВалентностьГлагола language=Russian
{
if context { безлич_глагол:пора{}.инфинитив:*{} }
then 2
}
// Быть сильным в чем-то неодушевленном:
// Он не силён в математике.
// ^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:сильный{КРАТКИЙ}.'в'.существительное:*{ одуш:неодуш } }
then 2
}
// дождаться сладкого
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дождаться{}.<OBJECT>НеодушОбъект{ падеж:род } }
then 2
}
// ---------------------------------------------------------------------------
// Дать+местоимение - обычно местоимение в дательном падеже:
// Я не дам им ничего
// ^^^^^^
// просто они дали выход злости.
// ^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:дать{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:дат } } }
then 5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:дать{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:дат } } }
then 5
}
// Артиллерии дам много.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}.{ <OBJECT>*:*{ ПАДЕЖ:РОД } наречие:много{} } }
then 6
}
// ---------------------------------------------------------------------------
// Подавим вариант с Генри/твор.п./
// Генри уловил кусочек фразы.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:уловить{}.<OBJECT>*:*{ одуш:одуш падеж:твор } }
then -5
}
// высокие колеса подняли тучи пыли.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поднять{}.<OBJECT>существительное:туча{ падеж:вин }.'пыли' }
then 3
}
// причинить животным страдания
// ^^^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:причинить{}.<OBJECT>'страдания'{ падеж:вин } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:причинять{}.<OBJECT>'страдания'{ падеж:вин } }
then 2
}
// Зачерпывать пюре большой ложкой
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:зачерпывать{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } }
then 1
}
// причинить животным страдания
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:причинять{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:причинять{}.<OBJECT>существительное:*{ одуш:одуш падеж:дат } }
then 1
}
// ТРЕБОВАТЬ обычно присоединяет неодушевленные в родительном падеже:
// наша честь требует свободы.
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:требовать{}.<OBJECT>существительное:*{ одуш:неодуш падеж:род } }
then 1
}
// Предпочтительно такое связывание, чтобы подлежащее для ПРИВЫКНУТЬ было обушевленным,
// либо было прямое дополнение в виде неодуш. объекта
// мечом привык решать любой спор.
// ^^^^^^ ^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:привыкнуть{}.<SUBJECT>существительное:*{ одуш:неодуш } }
then -2
}
// всем нужно спать на мягкой кровати
// ^^^^^^^^^^
tree_scorer language=Russian
{
if context { 'нужно'.'всем'{ падеж:дат } }
then 1
}
// Для модального глагола, к которому прикреплен инфинитив, нежелательно
// прикреплять еще и прямое дополнение:
//
// хочу все это понять
// ^^^^ ^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:хотеть{}.{
<INFINITIVE>*:*{}
<OBJECT>*:*{} } }
then -1
}
// чрезвычайная эмоциональная живость и легкомысленность партнера может меня обижать
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обижать{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// происходящее теряет всякое значение.
// ^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:терять{}.<OBJECT>существительное:значение{ падеж:вин } }
then 2
}
// пытаюсь не уснуть, выпивая много крепкого кофе, и заедая его шоколадом
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:заедать{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
} }
then 2
}
// Чтобы подавить распознавание БЫЛИ как существительного:
//
// Обвиняемые были освобождены в зале суда
// ^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { 'были'{ class:глагол }.{
<SUBJECT>прилагательное:*{ число:мн }
<RHEMA>прилагательное:*{ краткий страд число:мн }
} }
then 1
}
// кот спит и видит мышей во сне
// ^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:видеть{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
// Одушевленные субъекты обычно СПЯТ, а не СПАДАЮТ
// кенгуру, свернувшись клубком, спал
// ^^^^^^^ ^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:спать{}.<SUBJECT>существительное:*{ одуш:одуш падеж:им } }
then 1
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:спасть{}.<SUBJECT>существительное:*{ одуш:одуш падеж:им } }
then -4
}
// ГРЕТЬ ожидает прямое дополнение в вин.п.:
// Я хочу попить чаю, греющего душу
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:греть{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } }
then 1
}
// Кошки пили сливки несколько дней подряд
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пить{}.<OBJECT>существительное:*{ падеж:вин <в_класс>существительное:напиток{} } }
then 1
}
// Глагол БЫТЬ предпочинает паттер В+сущ в предл. падеже, а не в винительном:
// машина была в пути
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:быть{}.предлог:в{}.*:*{ падеж:предл } }
then 1
}
// настоящий смех приносит облегчение.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приносить{}.<OBJECT>существительное:облегчение{падеж:вин} }
then 2
}
// дважды раздался пронзительный свист.
// ^^^^^^^^ ^^^^^
wordentry_set То_Что_Раздается_Как_Звук=существительное:{
шум, свист, стук, звук, сигнал, рев, крик, бормотание, слово, фраза, гул, хохот, плач,
визг, хор, треск, смех, скрип, вопль, звон, выстрел
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:раздаться{}.<SUBJECT>То_Что_Раздается_Как_Звук }
then 1
}
// Обычно одушевленный субъект чешет неодушевленный предмет:
//
// Гарри почесал кончик носа.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:почесать{}.{
<SUBJECT>существительное:*{ падеж:им одуш:одуш }
<OBJECT>существительное:*{ падеж:вин одуш:неодуш }
} }
then 1
}
// цветок придал девушке уверенности.
// ^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:придать{}.<OBJECT>существительное:*{ одуш:неодуш падеж:род } }
then 1
}
// глухой рев наполнил окрестности.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:наполнить{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } }
then 1
}
// неторопливо допил прохладный сок.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:допить{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин <в_класс>существительное:напиток{} } }
then 1
}
/*
// Мы помогли ему влезть в лодку.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помочь{}.{
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
} }
then 5
}
*/
/*
// Разрешите вас пригласить?
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пригласить{}.<OBJECT>*:*{ падеж:вин } }
then 1
}
*/
// неторопливо допил прохладный сок.
// ^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:допить{}.<OBJECT>существительное:*{ падеж:вин одуш:неодуш <в_класс>существительное:напиток{} } }
then 1
}
// Он научил меня играть в шахматы.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:научить{}.{
<OBJECT>*:*{ падеж:вин }
инфинитив:*{}
} }
then 5
}
// Миша допил чай
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:допить{}.существительное:*{ падеж:вин одуш:неодуш } }
then 1
}
// Миша выпил чай
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:выпить{}.существительное:*{ падеж:вин одуш:неодуш } }
then 1
}
// Он смотрит на вещи просто.
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смотреть{}.предлог:на{}.существительное:*{ падеж:вин } }
then 1
}
// Оставь книгу у Лены.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оставить{}.предлог:у{}.существительное:*{ одуш:одуш } }
then 1
}
// кенгуру наловил детенышам мышей своими лапами
// ^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:наловить{}.<OBJECT>*:*{ падеж:род } }
then 1
}
// Автор воскресил героя из небытия
// ^^^^^^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:воскресить{}.предлог:из{}.'небытия' }
then 1
}
// Коля вызвался помочь с математикой
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помочь{}.предлог:с{}.существительное:*{ одуш:неодуш } }
then 1
}
// Поищите это слово в словаре.
// ^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поискать{}.предлог:в{}.существительное:*{ одуш:неодуш падеж:предл } }
then 1
}
// Всё это нашло отражение в его книге.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.<OBJECT>существительное:отражение{}.предлог:в{} }
then 3
}
// Я никого не встретил
// ^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { глагол:*{}.{ <NEGATION_PARTICLE>'не' 'никого'{падеж:вин} } }
then 1
}
// Никого не встретить
tree_scorer language=Russian
{
if context { инфинитив:*{}.{ <NEGATION_PARTICLE>'не' 'никого'{падеж:вин} } }
then 1
}
// Он никого не видел там кроме неё.
// ^^^^^^ ^^ ^^^^^
tree_scorer language=Russian
{
if context { глагол:*{}.{ <NEGATION_PARTICLE>'не' 'никого'{падеж:вин} } }
then 1
}
// напасть на спящих
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:напасть{}.предлог:на{}.*:*{ падеж:вин } }
then 1
}
// Мы с Мишей читали сказку
tree_scorer language=Russian
{
if context { местоимение:я{}.предлог:с{}.существительное:*{ падеж:твор одуш:одуш } }
then 1
}
// Мы с ней сидели за одной партой.
// ^^^^^^^^
tree_scorer language=Russian
{
if context { местоимение:я{}.предлог:с{}.местоимение:я{ падеж:твор } }
then 1
}
// Мы с ним были на концерте.
tree_scorer language=Russian
{
if context { местоимение:я{}.предлог:с{}.'ним'{ род:муж } }
then 1
}
// Аллах сотворил всякое животное из воды.
// ^^^^^^^^ ^^^^^^^
tree_scorer language=Russian
{
if context { rus_verbs:сотворить{}.предлог:из{} }
then 2
}
// Аллегра не сводила глаз с мужа.
// ^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { rus_verbs:сводить{}.{ <OBJECT>"глаз"{число:мн} предлог:с{}.*{падеж:твор} } }
then 2
}
// А вы были помолвлены с Лиллианой.
// ^^^^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:помолвленный{}.предлог:с{}.*{падеж:твор} }
then 2
}
// А ты с ним плохо обращаешься?
// ^^^^^ ^^^^^^^^^^^
tree_scorer language=Russian
{
if context { rus_verbs:обращаться{}.предлог:с{}.*{падеж:твор} }
then 2
}
// Он относится к бедному товарищу с горячим участием.
// ^^^^^^^^^ ^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { глагол:*{}.'с'.'участием' }
then 1
}
tree_scorer language=Russian
{
if context { инфинитив:*{}.'с'.'участием' }
then 1
}
tree_scorer language=Russian
{
if context { деепричастие:*{}.'с'.'участием' }
then 1
}
tree_scorer language=Russian
{
if context { прилагательное:*{ причастие }.'с'.'участием' }
then 1
}
// Она оправдала неявку на занятия болезнью.
// ^^^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оправдать{}.<OBJECT>*{ падеж:твор } }
then 1
}
// жаждать мести
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:жаждать{}.<OBJECT>'мести'{ падеж:род } }
then 1
}
// Он доводится мальчику дядей
// ^^^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:доводиться{}.<OBJECT>*:*{ падеж:твор } }
then 1
}
// принести в дом бездомного щенка
// ^^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:принести{}.<OBJECT>*:*{ падеж:вин } }
then 1
}
// всадить пулю в сердце
// ^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:всадить{}.предлог:в{}.существительное:*{ падеж:вин } }
then 1
}
// Усиленная работа отразилась на его здоровье.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отразиться{}.предлог:на{}.существительное:здоровье{ падеж:предл } }
then 1
}
#define PreferAccusObject(v) \
#begin
tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:v{}.<OBJECT>*:*{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { глагол:v{}.<OBJECT>*:*{ падеж:вин } } then 1 }
#end
// Поэты воспели в этой оде героев
PreferAccusObject(воспеть)
// встретить в классе старого приятеля (встретить+вин.п.)
PreferAccusObject(встретить)
// встречать в лесу голодного медведя (встречать+вин.п.)
PreferAccusObject(встречать)
// выписать из деревни нового скакуна
PreferAccusObject(выписать)
// регулярная армия вытесняет из пригородов повстанцев
PreferAccusObject(вытеснять)
// выводить с одежды пятна (вводить + вин.п.)
PreferAccusObject(выводить)
// выжать максимум из машины (выжать + вин.п.)
PreferAccusObject(выжать)
// собраться в аудитории
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:собраться{}.предлог:в{}.существительное:*{ одуш:неодуш падеж:предл <в_класс>существительное:помещение{} } }
then 1
}
// Глагол БОЯТЬСЯ обычно используется с прямым дополнением, причем одушевленное
// дополнение стоит в винительном падеже, а неодушевленное - в родительном.
// они должны научиться бояться нас.
// ^^^^^^^^^^^
// Дело мастера боится.
// ^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:бояться{}.<OBJECT>ОдушОбъект{ падеж:вин } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:бояться{}.<OBJECT>НеодушОбъект{ падеж:род } }
then 1
}
// сказал Холмс, снимая крышку с курицы
// ^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:снимать{}.предлог:с{}.*:*{ падеж:род } }
then 2
}
// Я послал книги по почте.
// ^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:послать{}.предлог:по{}.'почте' }
then 2
}
// Он разложил книги по всему столу.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:разложить{}.предлог:по{}.существительное:*{} }
then 1
}
// Мы покормили белок.
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:покормить{}.существительное:*{ падеж:вин одуш:одуш } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:покормить{}.существительное:*{ падеж:вин одуш:одуш } }
then 2
}
// писатель пишет повести
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:писать{ aux stress="пис^ать" }.существительное:*{ одуш:неодуш падеж:вин } }
then 1
}
// Резкий порывистый ветер валит прохожих с ног.
// ^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:валить{}.предлог:с{}.'ног' }
then 1
}
// Резкий порывистый ветер свалит тебя с ног.
// ^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:свалить{}.предлог:с{}.'ног' }
then 1
}
// блоггер, написавший про детский приют
tree_scorer language=Russian
{
if context { прилагательное:написавший{ aux stress="напис^авший" }.предлог:про{} }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:написать{ aux stress="напис^ать" }.предлог:про{} }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:написать{ aux stress="напис^ать" }.предлог:про{} }
then 1
}
// Учительница ищет в карманах шпаргалки
// ^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:искать{}.существительное:*{ падеж:вин } }
then 1
}
// заметившими косулю медведицами
// ^^^^^^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:заметить{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } }
then -2
}
// стирать белье в реке
// ^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:стирать{}.предлог:в{}.существительное:*{ одуш:неодуш падеж:предл } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:купить{}.предлог:у{}.существительное:*{ одуш:одуш } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:купить{}.предлог:у{}.местоимение:*{} }
then 2
}
// стирать прошлое из памяти
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:стирать{}.предлог:из{}.существительное:память{} }
then 1
}
// Боль исказила его лицо.
// ^^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:исказить{}.<OBJECT>существительное:лицо{ одуш:неодуш } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:искажать{}.<OBJECT>существительное:лицо{ одуш:неодуш } }
then 1
}
// Подавим по возможности связывание глагола ЕСТЬ с предложным дополнением ИЗ
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:есть{}.предлог:из{}.существительное:*{ <в_класс>существительное:овощ{} } }
then -1
}
// Винительное дополнение:
// считать деньги
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:считать{}.*:*{падеж:вин} }
then 1
}
// Мы согласовали наши законы с беларусским законодательством
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:согласовать{ вид:соверш }.предлог:с{} }
then 1
}
// Я иду в кино.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:идти{}.{
'в'.'кино'{ падеж:вин }
<SUBJECT>местоимение:*{}
} }
then 1
}
// Он купил игрушки для детей.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:купить{}.*:*{ падеж:вин } }
then 1
}
// Он занял деньги под большие проценты.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:занять{}.'деньги'{ падеж:вин } }
then 1
}
// его осторожность взяла верх над его жадностью
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:взять{}.существительное:верх{}.предлог:над{} }
then 1
}
// Студенты долго ломали голову над задачей.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ломать{}.{
'голову'
предлог:над{} } }
then 1
}
// Я не хотел вас обидеть.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обидеть{}.*:*{ падеж:вин } }
then 2
}
// Я нашёл толк в этом деле.
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.{
'толк'
предлог:в{}.существительное:*:*{ падеж:предл }
} }
then 1
}
// Я всюду искал письмо, но нигде не мог его найти.
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.*:*{ падеж:вин } }
then 2
}
// Я вовсе не хотел её оскорбить.
// ^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оскорбить{}.*:*{ падеж:вин } }
then 2
}
// Мы перебили врагов в бою.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:перебить{}.'в'.'бою' }
then 1
}
// Этот мотор делает 600 оборотов в минуту.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:делать{}.существительное:оборот{}.num_word:*{} }
then 3
}
// для ВЫУЧИТЬ желательно дополнение в винительном падеже
// Он выучил меня играть в шахматы.
// ^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:выучить{}.*:*{ падеж:вин } }
then 2
}
// Будем считать, что ЭТО в роли подлежащего имеет приоритет:
// Это внесло разнообразие в мою жизнь.
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:*{ время:прошедшее число:ед род:ср }.<SUBJECT>'это' }
then 1
}
// Я принёс эту книгу для вас.
// ^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:принести{}.предлог:для{}.местоимение:*{} }
then 1
}
// Глагол ИЗБРАТЬ обычно требует прямое дополнение в винительном падеже:
// Академия наук избрала его почётным членом.
// ^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:избрать{}.*:*{ падеж:вин } }
then 1
}
// Глагол ПРИСЫЛАТЬ обычно требует прямое дополнение
// Он присылал к должнику своих головорезов
// ^^^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:присылать{}.<OBJECT>существительное:*{ падеж:вин } }
then 1
}
// Я никого не встретил
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.{ частица:не{} 'никого'{ падеж:род } } }
then 1
}
// они затопили корабли в гавани
// ^^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:затопить{}.предлог:в{}.*:*{ падеж:предл } }
then 1
}
// Составьте предложение из этих слов.
// ^^^^^^^^^ ^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:составить{}.предлог:из{}.существительное:*{ одуш:неодуш падеж:род } }
then 1
}
// Согрейте руки у огня.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:согреть{}.предлог:у{}.существительное:*{ одуш:неодуш падеж:род } }
then 1
}
// Не оставь товарища в опасности.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оставить{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
// Я принёс книгу с собой.
tree_scorer ВалентностьГлагола language=Russian
{
if context { Гл_С_Твор.'с'.'собой' }
then 1
}
// Наш пароход держал курс прямо на север.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:держать{}.<OBJECT>существительное:курс{ падеж:вин } }
then 1
}
// Антонио ни с кем не говорил
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.{
'не'
'с'.{ 'ни' 'кем' }
} }
then 1
}
// Я был знаком с вашим дядей.
// ^^^^^^^^
tree_scorer language=Russian
{
if context { 'был'.{ прилагательное:знакомый{ краткий } предлог:с{}.существительное:*{ одуш:одуш } } }
then 3
}
tree_scorer language=Russian
{
if context { 'был'.{ прилагательное:знакомый{ краткий } предлог:с{}.местоимение:*{} } }
then 3
}
// Подавим родительную валентность для местоимения.
// Вас требует заведующий.
// ^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ ПАДЕЖ:ВИН }.<OBJECT>'вас'{падеж:вин} }
then 1
}
// Я научил его английскому языку.
// ^^^^^^ ^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:научить{}.{ <OBJECT>местоимение:я{падеж:вин} <OBJECT>*:*{падеж:дат} } }
then 1
}
// Я учу его английскому языку.
// ^^^ ^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:учить{}.{ <OBJECT>местоимение:я{падеж:вин} <OBJECT>*:*{падеж:дат} } }
then 1
}
// Я велел ему прийти через час.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:велеть{}.{ <OBJECT>местоимение:я{ падеж:дат } инфинитив:*{} } }
then 1
}
// Дождь помешал нам прийти.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помешать{}.{ <OBJECT>местоимение:я{ падеж:дат } инфинитив:*{} } }
then 1
}
// Ведь вы сами посоветовали мне так сделать.
// ^^^^^^^^^^^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:посоветовать{}.{ <OBJECT>местоимение:я{ падеж:дат } инфинитив:*{} } }
then 1
}
// Антонио разрешил нам рассказать об этом
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:разрешить{}.{ <OBJECT>местоимение:я{ падеж:дат } инфинитив:*{} } }
then 1
}
// кенгуру наловил детенышам мышей своими лапами
// ^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:наловить{}.<OBJECT>*:*{ падеж:род } }
then 1
}
// Характер писателя лучше всего выражается в его произведениях.
// ^^^^^^^^^^^
tree_scorer language=Russian
{
if context { наречие:всего{}.'лучше'{ class:наречие } }
then 1
}
// Этот город находится к западу от Москвы.
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:находиться{ вид:несоверш }.<SUBJECT>существительное:*{} }
then 1
}
// Он находится в весьма неприятном положении.
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:находиться{ вид:несоверш }.предлог:*{} }
then 1
}
// Подавим родительный падеж:
// Прошу вас.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:просить{}.местоимение:я{ падеж:вин } }
then 1
}
// Природа наградила его разнообразными способностями.
// ^^^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:наградить{}.местоимение:я{ падеж:вин } }
then 1
}
// Природа одарила его прекрасными способностями.
// ^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:одарить{}.местоимение:я{ падеж:вин } }
then 1
}
// Предпочтём винительный падеж местоимения, а не родительный.
// Вас спрашивает какой-то человек.
// ^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:спрашивать{}.'вас'{падеж:вин} }
then 1
}
// Примите мой искренний привет!
// ^^^^^^^ ^
tree_scorer language=Russian
{
if context { 'примите'{ наклонение:побуд }.'!' }
then 1
}
// Напишите фамилию полностью.
// ^^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:написать{aux stress="напис^ать"}.наречие:полностью{} }
then 1
}
// Она обозвала его дураком.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обозвать{}.{
*:*{ падеж:вин }
*:*{ падеж:твор }
} }
then 1
}
// Понизим достоверность распознавания УРКА:
// Девочка вообще не пошла на урок
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пойти{}.предлог:на{}.'урок'{ одуш:неодуш } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:идти{}.предлог:на{}.'урок'{ одуш:неодуш } }
then 1
}
// Выбираем винительный падеж:
// Время работает на нас.
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:работать{}.'на'.'нас'{падеж:вин} }
then 1
}
// Мы пришли к заключению, что он прав.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:придти{}.'к'.'заключению' }
then 1
}
/*
tree_scorer language=Russian
{
if context { 'два'{ class:числительное род:муж }.существительное:*{род:жен} }
then -1
}
tree_scorer language=Russian
{
if context { 'два'{ class:числительное род:муж }.существительное:*{род:ср} }
then -1
}
tree_scorer language=Russian
{
if context { 'два'{ class:числительное род:ср }.существительное:*{род:муж} }
then -1
}
tree_scorer language=Russian
{
if context { 'два'{ class:числительное род:ср }.существительное:*{род:жен} }
then -1
}
tree_scorer language=Russian
{
if context { числительное:два{род:жен}.существительное:*{род:жен} }
then 1
}
tree_scorer language=Russian
{
if context { числительное:два{род:ср}.существительное:*{род:ср} }
then 1
}
*/
// Уберем вариант СТАТЬ для:
//
// Он написал статью на русском языке.
// ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:написать{ aux stress="напис^ать" }.<OBJECT>'статью'{ падеж:вин } }
then 1
}
// Антонио подарил ведьмёнышам пюре
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подарить{}.{
<OBJECT>существительное:*{ падеж:вин одуш:неодуш }
<OBJECT>существительное:*{ падеж:дат одуш:одуш }
} }
then 1
}
// Дайте мне хлеба.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}.<OBJECT>существительное:хлеб{ падеж:вин } }
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}.<OBJECT>существительное:хлеб{ падеж:род } }
then 1
}
/*
wordentry_set НаречВремСуток=наречие:{ утром, вечером, днем, ночью }
// она вечером будет есть пюре
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.{
НаречВремСуток
инфинитив:*{}
} }
then 1
}
*/
// Глаголы с семантикой поедания, присоединяющие прямое дополнение в вин. падеже
wordentry_set ГлаголыПоедания_Вин=
{
глагол:есть{}, инфинитив:есть{}
}
// Антонио ест пюре
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.<OBJECT>'пюре'{падеж:вин} }
then 1
}
/*
// она утром будет есть пюре
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.<ATTRIBUTE>наречие:утром{} }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.'утром'{ class:существительное } }
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.'днем'{ class:существительное } }
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.'вечером'{ class:существительное } }
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.'ночью'{ class:существительное } }
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.<ATTRIBUTE>наречие:днем{} }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.<ATTRIBUTE>наречие:вечером{} }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.<ATTRIBUTE>наречие:ночью{} }
then 1
}
*/
// желая стать космонавтом
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:стать{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } }
then 1
}
// Царя над окрестностями
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:царить{}.'над'.'окрестностями' }
then 1
}
// Планета Юпитер не видна днём
// ^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:видный{ краткий }.<ATTRIBUTE>'днем'{} }
then 1
}
// Подавим распознавание ПОТОМ как существительного:
// вы едите пюре или суп, потом пьете чай
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.<OBJECT>'потом'{падеж:твор} }
then -100
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.<OBJECT>'потом'{падеж:твор} }
then -100
}
// Для глагола ЛОВИТЬ подавляем прямое дополнение в творительном падеже, если
// оно соответствует одушевленному:
// Антонио опять ловит мышь несколько ночей подряд
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ловить{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } }
then -1
}
// продавать книги
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:продавать{}.<OBJECT>существительное:*{ падеж:вин } }
then 1
}
// мы не увидели тебя
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:увидеть{}.<OBJECT>местоимение:*{ падеж:вин } }
then 1
}
// Винительная валентность глагола ГОВОРИТЬ используется
// только с неодушевленным дополнением.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:говорить{}.<OBJECT>*{ падеж:вин } }
then -1
}
// кот не видит ее
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:видеть{}.<OBJECT>местоимение:я{ падеж:вин } }
then 1
}
// кот увидел кенгуру на полу
// ^^^^^^ ^^^^^^^
// Подавим вариант творительного падежа для любых дополнение, за исключением ГЛАЗ
// а неодушевленные пусть будут "увидел своими глазами"
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:увидеть{}.<OBJECT>существительное:глаз{ падеж:твор } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:видеть{}.<OBJECT>существительное:глаз{ падеж:твор } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:увидеть{}.<OBJECT>существительное:*{ падеж:твор } }
then -1
}
// Дмитрий Иванович Менделеев увидел периодическую таблицу элементов во сне
// ^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:увидеть{}.'во'.'сне' }
then 1
}
// аналогично для:
// кот видит кенгуру на полу
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:видеть{}.<OBJECT>существительное:*{ падеж:твор } }
then -1
}
// Для глагола ВСТРЕТИТЬ подавим прямое дополнение в творительном падеже, если
// оно - одушевленный объект:
// ведьмёныш встретил Антонио
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:встретить{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } }
then -1
}
// Аналогично: ведьмёныш встречал Антонио веселым криком
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:встречать{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } }
then -1
}
wordentry_set ЧтоМожноДелатьСЧаем=
{
инфинитив:налить{},
глагол:налить{}
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ЧтоМожноДелатьСЧаем.<OBJECT>'чаю'{падеж:парт} }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:ловить{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
// мыть руки с мылом
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:мыть{}.'с'.'мылом' }
then 1
}
// Я мою руки с мылом
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:мыть{}.'с'.'мылом' }
then 1
}
// кошки собираются ловить хозяину в амбаре мышь
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:ловить{}.'в'.'амбаре' }
then 1
}
// Мы боремся все доступными средствами с ошибками в программе
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:бороться{}.'с'.'ошибками' }
then 1
}
// большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:высадиться{}.'для'.'поиска' }
then 1
}
// стипендия студента университета дружбы народов, живших в союзных республиках бывшего СССР
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:живший{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
// студенты университета, построенного в СССР
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:построенный{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
// группа студентов университета дружбы народов, основанного в СССР
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:основанный{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
// группа студентов университета дружбы народов, активно пропагандировавшейся в СССР
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:пропагандировавшийся{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { 'сыплет'{class:глагол}.<SUBJECT>существительное:дождь{ падеж:им } }
then 1
}
tree_scorer language=Russian
{
if context { безлич_глагол:стало{}.'всем'{ class:прилагательное падеж:дат} }
then 1
}
// давай-ка выпей молока
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:выпить{}.'молока'{class:существительное} }
then 1
}
// лежащий на полу
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:лежащий{}.предлог:на{}.'полу'{падеж:мест} }
then 1
}
// Подавим распознавание ДНЁМ как существительного в творительном падеже.
//
// кошки днем обычно ели и дремали
// ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:есть{}.<OBJECT>существительное:день{ падеж:твор } }
then -1
}
// Несмотря на появляющуюся родительную валентность в отрицательной форме глагола,
// местоимения её и его надо брать только в аккузативе.
// она её не съест
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:съесть{}.'ее'{ падеж:вин } }
then 1
}
/*
// Планета Марс видна утром
tree_scorer language=Russian
{
if context { прилагательное:видный{}.наречие:утром{} }
then 1
}
*/
/*
// Повысим достоверность безличного глагола.
//
// Грести стало труднее
// ^^^^^
tree_scorer language=Russian
{
if context { 'стало'{class:безлич_глагол} }
then 1
}
*/
// Для глагола КУПИТЬ надо подавлять связывание с прямым дополнением в родительным падеже
// для живых существ.
// Ну же, купите слона!
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:купить{}.<OBJECT>существительное:*{ ОДУШ:ОДУШ падеж:род } }
then -1
}
// купи кефиру
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:купить{}.<OBJECT>существительное:*{ ОДУШ:НЕОДУШ падеж:парт } }
then 4
}
// налей мне воды
// ^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:налить{}.<OBJECT>'воды'{ падеж:род } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:лежать{}.'в'.'углу' }
then 1
}
// ОСВЕТИТЬ можно обычно КОМУ-ТО, а не чему-то:
// отблеск молнии осветил часового.
// ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:осветить{}.существительное:*{ падеж:дат одуш:неодуш } }
then -10
}
// Он ездит на работу на автобусе.
// ^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ездить{}.предлог:на{}.существительное:*{ падеж:предл одуш:неодуш <в_класс>существительное:транспорт{} } }
then 2
}
// Его успех доставил ей радость.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:доставить{}.{ <OBJECT>ОдушОбъект{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } }
then 2
}
/*
// Предотвращаем отрыв слова ЭТОТ, ЭТОЙ и т.д. от существительного.
// Роберт улыбнулся этой мысли.
// ^^^^^^^^^^
tree_scorer language=Russian
{
if context { существительное:*{}.<ATTRIBUTE>прилагательное:этот{} }
then 2
}
*/
// Речки разлились и дороги стали непроходимы.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:стать{}.прилагательное:*{ краткий } }
then 1
}
// укрыться от дождя под навесом
// ^^^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:укрыться{}.предлог:под{}.НеодушОбъект }
then 2
}
// Мул - помесь осла и лошади.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { существительное:помесь{}.существительное:*{}.союз:и{} }
then 1
}
// Олег обвел взглядом окрестности.
// ^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обвести{}.<OBJECT>*:*{ падеж:вин } }
then 1
}
// Олег хмуро окинул взглядом убитого.
// ^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:окинуть{}.<OBJECT>*:*{ падеж:вин } }
then 1
}
// мои предки построили его собственными руками.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:построить{}.<OBJECT>НеодушОбъект{ падеж:вин } }
then 5
}
// иначе им грозит беда.
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:грозить{}.<OBJECT>*:*{ падеж:дат } }
then 1
}
// Джим поискал глазами своего коня.
// ^^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поискать{}.<OBJECT>ОдушОбъект{ падеж:вин } }
then 1
}
// вера дает им силу.
// ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:давать{}.<OBJECT>*:*{ падеж:дат } }
then 1
}
// им дорого обойдется сегодняшний бой.
// ^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обойтись{}.<OBJECT>*:*{ падеж:дат } }
then 1
}
// киммериец молча пожал ей руку.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пожать{}.{ <OBJECT>ОдушОбъект{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } }
then 1
}
// ей ответил пронзительный яростный визг.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ответить{2}.<OBJECT>местоимение:я{ 1 падеж:дат } }
then 1
}
// Он ответил Джо
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ответить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } }
then 2
}
// зачем давать им пустую надежду.
// ^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пожать{}.{ <OBJECT>ОдушОбъект{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } }
then 2
}
// тебе следовало оставить ей записку.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оставить{}.{ <OBJECT>ОдушОбъект{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } }
then 2
}
// маленький желтый череп улыбнулся ей.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:улыбнуться{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } }
then 2
}
// Томас швырнул ей птицу.
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:швырнуть{1}.{ <OBJECT>ОдушОбъект{ 2 падеж:дат } <OBJECT>*:*{ падеж:вин } } }
then 2
}
// дом чрезвычайно понравился ей.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:понравиться{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 2
}
// меч им явно нравился.
// ^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:нравиться{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 2
}
// некоторым действительно нравится моя работа.
// ^^^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:нравиться{}.<OBJECT>прилагательное:*{ падеж:дат число:мн ~краткий } }
then 4
}
// лунный свет помогал им.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помогать{}.<OBJECT>*:*{ падеж:дат } }
then 3
}
// им необходимо было помочь.
// ^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помочь{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помогать{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 2
}
// мой отец убит им.
// ^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:убитый{}.<OBJECT>*:*{ падеж:твор } }
then 1
}
// ей надо уйти отсюда.
// ^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:надо{}.{ ОдушОбъект{ падеж:дат } инфинитив:*{} } }
then 1
}
// ей вдруг захотелось уйти.
// ^^^ ^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:захотелось{}.{ ОдушОбъект{ падеж:дат } инфинитив:*{} } }
then 1
}
// капитан пожал им руки.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пожать{}.{ <OBJECT>*:*{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } }
then 2
}
// хозяин жеребца снова закричал. (закричать можно ЧТО-ТО, но не КОГО-ТО)
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:закричать{}.<OBJECT>ОдушОбъект{ падеж:вин } }
then -100
}
// ей явно понравился ответ.
// ^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:понравиться{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 1
}
// остальным предстояло помогать им.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помогать{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 1
}
// им стало вдруг зябко.
// ^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:стало{}.ОдушОбъект{ падеж:дат } }
then 1
}
// нам стало жалко бедного котенка
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:жалко{}.ОдушОбъект{ падеж:дат } }
then 2
}
// император осторожно коснулся пальцами белой перчатки.
// ^^^^^^^^ ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:коснуться{}.<OBJECT>*:*{ падеж:род } }
then 1
}
// обычно ПРОТЯНУТЬ кому-то, а не чему-то:
// тот протянул руку помощи.
// ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:протянуть{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -5
}
// возле всякой двери тебя ждала такая же ловушка.
// ^^^^^^^^^^
// однако сперва ее ждало глубокое разочарование.
// ^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ждать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подождать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
// однако ему удалось открыть нечто интересное.
// ^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:открыть{}.<OBJECT>НеодушОбъект{ падеж:вин } }
then 1
}
// однако название мне удалось прочитать.
// ^^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:прочитать{}.<OBJECT>НеодушОбъект{ падеж:вин } }
then 1
}
// пройти можно ЧТО-ТО:
// ты уже прошел его так много раз.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пройти{}.<OBJECT>ОдушОбъект{ падеж:вин } }
then -1
}
/*
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пройти{}.<OBJECT>НеодушОбъект{ падеж:вин } }
then 1
}
*/
// злость прошла довольно давно.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пройти{}.<SUBJECT>НеодушОбъект }
then 1
}
// затем стал внимательно изучать глаз юноши.
// ^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:изучать{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// комната ожидания полна народу.
// ^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:полный{ краткий }.существительное:*{ падеж:род } }
then 1
}
tree_scorer language=Russian
{
if context { прилагательное:полный{ краткий }.существительное:*{ падеж:парт } }
then 1
}
// развалиться на части
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:развалиться{}.'на'.'части'{ падеж:вин } }
then 2
}
// ВЗЯТЬ можно КОМУ-ТО, а не ЧЕМУ-ТО:
// полковник взял микрофон внутренней связи.
// ^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:взять{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -5
}
// оставался единственный способ проверить корабль.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:проверить{}.<OBJECT>*:*{ падеж:вин } }
then 1
}
// ТРЕБОВАТЬ можно кому-то, а не чему-то:
// моя месть требует радости охоты.
// ^^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:требовать{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -5
}
// ПРОДОЛЖИТЬ можно ЧТО-ТО неодушевленное:
// вскоре отряд продолжил путь.
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продолжить{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продолжить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then -1 }
// Ломать душу
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ломать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ломать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 1 }
// я доволен им
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:довольный{ краткий }.<OBJECT>*:*{ падеж:твор } }
then 2
}
// Обычно получить можно кому-то, а не чему-то:
// поэтому хотим получить максимум информации.
// ^^^^^^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:получить{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -2
}
// пришла пора сделать следующий шаг.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:прийти{}.<SUBJECT>существительное:пора{}.инфинитив:*{} }
then 1
}
// убить КОГО-ТО:
// ты должен его убить!
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:убить{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:убивать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:убить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:убивать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// мне едва удалось его спасти.
// ^^^ ^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:удалось{}.<SUBJECT>ОдушОбъект{ падеж:дат } }
then 2
}
// им удалось вытащить его из озера.
// ^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:удалось{}.<SUBJECT>*:*{ падеж:дат } }
then 1
}
// ЕДА не может быть продавцом:
// В булочной продают хлеб, булки, печенье.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:продавать{}.<SUBJECT>существительное:*{ <в_класс>существительное:еда{} } }
then -100
}
// ОБЪЯСНИТЬ можно обычно кому-то:
// происхождение информации объясню позднее.
// ~~~~~~~~~~ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:объяснить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:объяснить{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 1 }
#region СОЗДАВАТЬ
// если получатель действия находится слева от глагола, то штрафуем:
// банки памяти создавали самую большую проблему.
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:создавать{ 2 }.<OBJECT>*:*{ падеж:дат 1 } }
then -1
}
// Но компенсируем предыдущее правило, если получатель - одушевленный:
// нам создали тепличные условия
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:создавать{ 2 }.<OBJECT>ОдушОбъект{ падеж:дат 1 } }
then 1
}
#endregion СОЗДАВАТЬ
// Обычно ПОКАЗАТЬСЯ можно КОМУ-ТО:
// показалась машина местной полиции.
// ^^^^^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показаться{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показаться{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 1 }
// БЕЖАТЬ можно чем-то неодушевленным, например - БЕРЕГОМ:
// бегущим по берегу псом
// ^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:бежать{}.<OBJECT>ОдушОбъект{ падеж:твор } } then -100 }
// Чтобы подавить распознавание существительным "БЫЛЬ":
// "Обвиняемые были освобождены в зале суда"
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:быть{ 2 }.<SUBJECT>прилагательное:*{ падеж:им ~краткий степень:атриб 1 } }
then 2
}
// ПОИСКАТЬ обычно можно КОМУ-ТО:
// Давайте поищем примеры реализации этой функции
// ^^^^^^ ~~~~~~~~~~ ~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поискать{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -1
}
// Обычно ПРИХОДИТ КОМУ-ТО, а неодушевленный реципиент возможет лишь в
// особых оборотах типа КОНЕЦ ПРИШЕЛ ЭТОЙ АФЕРЕ.
// неизвестно откуда пришло вдруг чувство опасности.
// ^^^^^^ ~~~~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прийти{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -3 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:придти{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -3 }
// советую вам исправить свою ошибку.
// ^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:советовать{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 2
}
// Подавим связывание ПРИШЛО и ПОЗАБОТИТЬСЯ исходя из того, что обычно
// только одушевленные субъекты приходят сделать что-то:
// однако пришло время позаботиться о собственной безопасности.
// ^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:придти{}.{ <SUBJECT>НеодушОбъект инфинитив:*{} } } then -1 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:прийти{}.{ <SUBJECT>НеодушОбъект инфинитив:*{} } } then -1 }
// Зайти можно КОМУ-ТО
// сам зашел снаружи конструкции противника.
// ^^^^^ ~~~~~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:зайти{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
// обычно глагол ЗАНЯТЬ идет с винительным дополнением:
// эти приготовления заняли целый день.
// ^^^^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:занять{}.<OBJECT>*:*{ падеж:вин } } then 1 }
// Сжать обычно можно КОМУ-ТО:
// Олег изо всех сил сжал челюсти.
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:сжать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
// после начала битвы прошли считанные секунды.
// ^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:пройти{}.<SUBJECT>ИнтервалВремени{ ПАДЕЖ:ИМ } }
then 1
}
// желаю тебе найти принца.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:желать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 1
}
// Он рекомендовал мне сделать это.
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:рекомендовать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 1
}
// Он угрожал мне бросить работу.
// ^^^^^^^ ^^^ ~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:угрожать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 1
}
// позволю себе напомнить историю вопроса.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:позволить{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 1
}
// Олег хмуро окинул взглядом убитого.
// ^^^^^^ ^^^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:окинуть{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>'взглядом' } }
then 1
}
// где же моя благодарность?
// ^^^^^^ ^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { наречие:где{}.{ частица:же{} существительное:*{ падеж:им } } }
then 1
}
// кому хочется есть
// ^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:хочется{}.<SUBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 1
}
// нам нужно только доставить его туда.
// ^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:нужно{}.<SUBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 2
}
// ТОРЖЕСТВОВАТЬ можно ЧТО-ТО неодушевленное:
// Весь день и весь вечер шумел и торжествовал народ по всему королевству
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:торжествовать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } }
then -100
}
// МЕШАТЬ кому-то ДЕЛАТЬ что-то
// страх мешал ей плакать.
// ^^^^^ ^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:мешать{}.{ <OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } инфинитив:*{} } }
then 2
}
// ПОВТОРИТЬ можно обычно КОМУ-ТО, а не ЧЕМУ-ТО
// мастер песни повторил вопрос.
// ~~~~~ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:повторить{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -10
}
// вскоре подошел поезд метро.
// ^^^^^^^ ~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подойти{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -10
}
// ОТКРЫВАТЬСЯ можно обычно КОМУ-ТО
// новый мир открывался после каждой мили пути.
// ^^^^^^^^^^ ~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:открываться{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -10
}
// Обычно СЛОЙ покрывает что-то, даже если порядок слов обратный нормальному:
// пол покрывал толстый слой пыли.
// ^^^^^^^^ ^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:покрывать{}.{ <SUBJECT>существительное:слой{} НеодушОбъект{ ПАДЕЖ:ВИН } } }
then 2
}
// Ей нравится ходить туда.
// ^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:нравилось{}.<SUBJECT>*:*{ ПАДЕЖ:ДАТ } }
then 2
}
// оставался единственный способ проверить корабль.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:проверить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then 2
}
// кому вы отдали его?
// ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:*{}.<OBJECT>'кому'{ падеж:дат class:местоим_сущ } }
then 2
}
// кому может понадобиться старая чужая лодка?
// ^^^^ ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:*{}.<OBJECT>'кому'{ падеж:дат class:местоим_сущ } }
then 2
}
// Не смей мне врать!
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:врать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 2
}
// меня все здесь боятся!
// ^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:бояться{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } }
then 1
}
// Он мучает её своим бесчувствием.
// ^^^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:мучить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then 1
}
// почему ты позволил им упасть?
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:позволить{}.<OBJECT>*:*{ падеж:дат } }
then 2
}
// разве обычные люди могут читать мысли?
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:читать{}.<OBJECT>НеодушОбъект{ падеж:вин } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:читать{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 1
}
// НАЗЫВАТЬ обычно идет с винительным дополнением:
// все его называют сегодня мальчиком.
// ^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:называть{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// Подавляем присоединение послелогов к существительным:
// недалеко от него лежал человек лицом вниз.
// ~~~~~~~ ^^^^^^^^^^
tree_scorer language=Russian { if context { существительное:*{}.послелог:вниз{} } then -10 }
tree_scorer language=Russian { if context { существительное:*{}.послелог:вверх{} } then -10 }
tree_scorer language=Russian { if context { существительное:*{}.послелог:вперед{} } then -10 }
// Показывать на одушевленного (вин) - это важно, если объект несклоняемый:
// Вадим показал на Элен
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:показать{}.предлог:на{}.ОдушОбъект{ падеж:вин } }
then 1
}
// пора им всем возвращаться домой.
// ~~~~~~~ ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:возвращаться{}.ОдушОбъект{ падеж:твор } }
then -10
}
// мама души не чаяла в своих детях
// ~~~~ ^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:чаять{}.<OBJECT>существительное:душа{} }
then 30
}
// Комар носа не подточит.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подточить{}.{ частица:не{} <OBJECT>существительное:нос{} } }
then 30
}
/*
// с тех пор ты видел его всего несколько раз.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { наречие:всего{}.наречие:несколько{}.существительное:раз{} }
then 2
}
*/
// Руперт вопреки себе улыбнулся.
// ^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.предлог:вопреки{} }
then 2
}
// вам следует проверить Марину согласно инструкции.
// ^^^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.предлог:согласно{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.предлог:согласно{} } then 2 }
// убийство для них естественно.
tree_scorer language=Russian { if context { прилагательное:естественный{}.предлог:для{} } then 2 }
// Пусть предложное дополнение с У присоединяется к глаголу, а не к существительному:
// ноги у меня болели.
// ^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.предлог:у{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.предлог:у{} } then 2 }
// Антон ее так назвал.
// ^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:назвать{}.<OBJECT>*:*{ падеж:вин } }
then 1
}
// Наречие ЧАСТО служит косвенным признаком изъявительной, а не императивной формы глагола:
// ты часто ешь хлеб
// ^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ наклонение:побуд }.наречие:часто{} }
then -2
}
// Наречие ОЧЕНЬ служит косвенным признаком изъявительной, а не императивной формы глагола:
// вы очень любите ягоды
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ наклонение:побуд }.наречие:очень{} }
then -2
}
// несколько дней спустя путников ожидал приятный сюрприз.
// ^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ожидать{}.ОдушОбъект{ ПАДЕЖ:ВИН } }
then 1
}
// ПРИВЛЕЧЬ обычно можно КОГО-ТО одушевленного:
// Его привлекли к ответственности за нарушение порядка.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:привлечь{}.ОдушОбъект{ ПАДЕЖ:ВИН } }
then 1
}
// Его целый год держали в тюрьме.
// ^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:держать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then 4
}
// ОБЕЩАТЬ КОМУ-ТО СДЕЛАТЬ что-то:
// ты обещал мне показать корабль!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обещать{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } }
then 2
}
// чиновник приказал ему открыть два кожаных мешка.
// ^^^^^^^^ ^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приказать{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } }
then 5
}
// ++++++++++++++++++++++++++++++++++++++++
// мне обещали все вернуть назад
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обещать{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } }
then 5
}
// ++++++++++++++++++++++++++++++++++++++++
// мне обещали все вернуть назад
// Его гордость не позволяла ему просить об одолжении.
// ^^^^^^^^^ ^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:позволять{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:позволить{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } } then 2 }
// такое устройство для моих целей бесполезно.
// ~~~~~~~~~~ ^^^ ^^^^^^^^^^
tree_scorer language=Russian { if context { прилагательное:бесполезный{}.предлог:для{} } then 2 }
// ДАТЬ отчет можно обычно КОМУ-ТО, а не чему-то:
// Он дал подробный отчёт о своей поездке.
// ^^^ ^^^^^ ~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}.{ <OBJECT>существительное:отчет{} <OBJECT>НеодушОбъект{ПАДЕЖ:ДАТ} } }
then -10
}
// отстегнуть маме денег
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отстегнуть{}.{ <OBJECT>НеодушОбъект{ падеж:род } <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} } }
then 5
}
// все вас боятся
// ~~~~~~~
tree_scorer language=Russian
{
if context { 'вас'.'все'{class:прилагательное} }
then -100
}
// Я работаю учителем в сельской школе
// ^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:работать{}.предлог:в{}.*:*{падеж:предл} } then 2 }
// небеса для меня закрыты.
// ^^^ ^^^^^^^^
tree_scorer language=Russian { if context { прилагательное:закрытый{}.предлог:для{} } then 2 }
// Это такое трудное слово, что он не может его запомнить.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:запомнить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// Его утомляла долгая ходьба.
// ^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:утомлять{}.ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:утомить{}.ОдушОбъект{ падеж:вин } } then 2 }
// но где удалось его добыть?
// ^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:добыть{}.НеодушОбъект{ падеж:вин } } then 2
}
// кладбище от моря довольно далеко
// ~~~~~~~~ ^^ ^^^^^^
tree_scorer language=Russian { if context { прилагательное:далекий{}.предлог:от{} } then 2 }
// мы внедряем в жизнь идеи великих ученых
// ^^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:внедрять{}.<OBJECT>НеодушОбъект{ПАДЕж:ВИН} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:внедрить{}.<OBJECT>НеодушОбъект{ПАДЕж:ВИН} } then 2 }
// неужели разговор его окончательно сломал?
// ^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:переломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обламывать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 }
// Критика должна составлять душу журнала.
// ^^^^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:составлять{1}.<OBJECT>НеодушОбъект{ 2 ПАДЕж:ВИН} } then 1 }
// ПОРАЗИТЬ обычно можно КОГО-ТО, а не чего-то:
// однако его глубоко поразило одно событие.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поразить{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } }
then 2
}
// такое положение вещей его вполне устраивает.
// ^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:устраивать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:устроить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// Обычно ПОИСКАТЬ можно КОМУ-ТО, а не чему-то:
// Давайте поищем примеры реализации этой функции
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поискать{}.<OBJECT>НеодушОбъект{ПАДЕж:ДАТ} } then -1 }
// Давать КОМУ-ТО ЧЕГО-ТО:
// Рита дает девочке хлеба.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:давать{}.{
<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ }
<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД }
}
}
then 5
}
// Я дам им чаю
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}.{
<OBJECT>*:*{ ПАДЕЖ:ДАТ }
<OBJECT>*:*{ ПАДЕЖ:ПАРТ }
}
}
then 5
}
// попросил передать управление станции.
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:передать{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ДАТ }
}
}
then 5
}
// ЕСТЬ могут обычно только одушевленные:
// Антонио ест суп и пюре
// ^^^^^^^ ^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:есть{}.{ <SUBJECT>ОдушОбъект{} <OBJECT>*:*{ падеж:вин } } }
then 1
}
/*
// есть несколько возможных вариантов.
tree_scorer language=Russian
{
if context { rus_verbs:быть{}.наречие:несколько{}.существительное:*{} }
then 1
}
*/
// Мы можем использовать эти сюжеты в молитвах.
// ^^^^^^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:использовать{}.предлог:в{}.*:*{ падеж:предл } }
then 2
}
// ЛУЧШЕ+инфинитив является очень частотным паттерном, в отличие от использования ЛУЧШЕ в качестве
// простого атрибута глагола (как в СТАРАЙСЯ ЛУЧШЕ!)
// лучше избавиться от обезьяны
// ^^^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { безлич_глагол:лучше{1}.инфинитив:*{2} } then 2
}
// ПОКОРМИТЬ можно кого-то одушевленного:
// Мы покормили белок.
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:покормить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:кормить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:накормить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
// СЛУШАТЬСЯ кого-то/вин:
// слушаться родителей
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:слушаться{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:послушаться{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
// ПОЛОЖИТЬ кого-то/вин/:
// Нам придётся положить его в больницу.
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:положить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ложить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
// ХОТЕТЬ кому-то одуш
// хочу кофе
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:хотеть{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// КАК обычно является наречием, модифицирующим глаголы и инфинитивы
// однако как остановить профессора?
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{2}.<ATTRIBUTE>наречие:как{1}.[not]*:*{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{2}.<ATTRIBUTE>наречие:как{1}.[not]*:*{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { безлич_глагол:*{2}.<ATTRIBUTE>наречие:как{1}.[not]*:*{} } then 2 }
// кроме того, КАК может атрибутировать наречия:
tree_scorer language=Russian { if context { наречие:*{ степень:атриб }.<ATTRIBUTE>наречие:как{} } then 1 }
// как будто они нас понимают
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<ATTRIBUTE>наречие:как будто{} } then 7 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.<ATTRIBUTE>наречие:как будто{} } then 7 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { прилагательное:*{ причастие краткий }.<ATTRIBUTE>наречие:как будто{} } then 7 }
// внутри все выглядело как всегда
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<ATTRIBUTE>наречие:как всегда{} } then 7 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.<ATTRIBUTE>наречие:как всегда{} } then 7 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { прилагательное:*{ причастие краткий }.<ATTRIBUTE>наречие:как всегда{} } then 7 }
// сегодня все было как обычно
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<ATTRIBUTE>наречие:как обычно{} } then 7 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.<ATTRIBUTE>наречие:как обычно{} } then 7 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { прилагательное:*{ причастие краткий }.<ATTRIBUTE>наречие:как обычно{} } then 7 }
/*
// наречие КАК обычно не стоит справа от глагола в одиночку.
// убью как собаку.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{1}.<ATTRIBUTE>наречие:как{2}.[not]*:*{} }
then -10
}
*/
// Олег вытянул вперед руки
// ^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вытянуть{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вытягивать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
// теперь она могла его толком рассмотреть.
// ^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<ATTRIBUTE>наречие:толком{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.<ATTRIBUTE>наречие:толком{} } then 2 }
// они быстро пересекли плато
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пересечь{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пересекать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
// Как вызвать такси?
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вызвать{}.<OBJECT>*:*{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вызывать{}.<OBJECT>*:*{ падеж:вин } } then 1 }
// наверху их охватил морской ветер.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:охватить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// Чиновник уже пообещал, что не будет покрывать своего родственника
// ^^^^^^^^^ ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:покрывать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then 2
}
// Толстые линии показывают связи между участками коры
// ^^^^^^^^^^ ~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показывать{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показывать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } } then 2 }
// Олег хмуро окинул взглядом убитого.
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:окинуть{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// по левой стороне груди текла кровь.
// ~~~~~ ^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:течь{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -2 }
// это может лишить наше общество работы
// ^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:лишить{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:лишать{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД } } then 2 }
// сбивая их сильной струей воды с надводной растительности
// ^^^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сбивать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сбить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// Лидеры организации хасидов заявили, что деньги их не интересуют
// ^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:интересовать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// как радостно за руку ее схватили!
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:схватить{}.<OBJECT>местоимение:я{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:хватать{}.<OBJECT>местоимение:я{ ПАДЕЖ:ВИН } } then 2 }
// Антон поднес ладони к горлу
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поднести{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подносить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// оставшиеся вынуждены по очереди помогать ей двигаться вперед
// ^^^^^^^^^ ^^^^^^^^
tree_scorer language=Russian { if context { прилагательное:вынужденный{}.инфинитив:*{} } then 2 }
// Артур погладил по носу старого коня
// ^^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:погладить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:гладить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// ты можешь нас туда провести?
// ^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:провести{}.<OBJECT>местоимение:я{ ПАДЕЖ:ВИН } } then 1 }
// провожают обычно одушевленные объекты,
tree_scorer ВалентностьГлагола language=Russian { if context { глагол:проводить{ вид:соверш }.<OBJECT>НеодушОбъект{ падеж:вин } } then -5 }
tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:проводить{ вид:соверш }.<OBJECT>НеодушОбъект{ падеж:вин } } then -5 }
tree_scorer ВалентностьГлагола language=Russian { if context { глагол:проводить{ вид:несоверш }.<OBJECT>ОдушОбъект{ падеж:вин } } then -5 }
tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:проводить{ вид:несоверш }.<OBJECT>ОдушОбъект{ падеж:вин } } then -5 }
// у ворот всадников проводили жесткие темные глаза стражи
tree_scorer ВалентностьГлагола language=Russian { if context { глагол:проводить{ вид:соверш }.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
// но это мешало им
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:мешать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помешать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:препятствовать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
// его можно предотвратить
// ^^^ ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предотвратить{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предотвращать{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предотвратить{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } } then -10 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предотвращать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } } then -10 }
// им хорошо платят
// ^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:платить{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заплатить{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
// Гарри взял
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:взять{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:РОД } } then -1 }
// сигареты у него забрали
tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:забрать{}.<SUBJECT>НеодушОбъект } then -1 }
tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:брать{}.<SUBJECT>НеодушОбъект } then -1 }
tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:забирать{}.<SUBJECT>НеодушОбъект } then -1 }
// тот принял ее мертвой рукой.
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:принять{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:принимать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// В США миллионера осудили за попытку продать Ирану детали для ракет ПВО
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:осудить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:осуждать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// Африканский союз позвал войска НАТО в Мали
// ^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:позвать{}.предлог:в{}.*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:звать{}.предлог:в{}.*:*{ падеж:вин } } then 2 }
// вряд ли это им понравится.
// ^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:понравиться{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
// слушайся меня
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:слушаться{}.<OBJECT>*:*{ ПАДЕЖ:РОД } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:послушаться{}.<OBJECT>*:*{ ПАДЕЖ:РОД } } then 2 }
// все это ее непосредственно касалось.
// ^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:коснуться{}.<OBJECT>*:*{ ПАДЕЖ:РОД } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:касаться{}.<OBJECT>*:*{ ПАДЕЖ:РОД } } then 2 }
// а громадный глаз подмигнул им
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подмигнуть{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подмигивать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
// ты мог бы им помочь.
// ^^ ^^^^^^
//tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помочь{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
//tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помогать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
// воины окружили их кольцом.
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:окружить{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>НеодушОбъект{ ПАДЕЖ:ТВОР } } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:окружать{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>НеодушОбъект{ ПАДЕЖ:ТВОР } } } then 2 }
// кому теперь нужны новые программы?
// ^^^^ ^^^^^
tree_scorer language=Russian { if context { прилагательное:нужный{}.<OBJECT>местоим_сущ:кто{ ПАДЕЖ:ДАТ } } then 2 }
// именно твое мнение для нас крайне важно.
// ^^^ ^^^^^
tree_scorer language=Russian { if context { прилагательное:важный{}.предлог:для{} } then 2 }
// от него ждали реакции.
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ждать{}.{ <OBJECT>НеодушОбъект{ ПАДЕЖ:РОД } предлог:от{} } } then 2 }
// протер от пыли глаза.
// ^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:протереть{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:притирать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// ты предпочел камни моей жизни.
// предпочесть ЧТО-ТО ЧЕМУ-ТО
tree_scorer ВалентностьГлагола language=Russian
{
if context {
rus_verbs:предпочесть{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:дат }
}
} then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context {
rus_verbs:предпочитать{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:дат }
}
} then 2
}
// мы вынуждены просить вашей помощи.
// ^^^^^^^ ~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:просить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:запросить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// Наречие ТАК обычно не модифицирует наречия места и времени:
// так где ты был?
tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:МЕСТО }.наречие:так{} } then -100 }
tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:НАПРАВЛЕНИЕ }.наречие:так{} } then -100 }
tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:НАПРАВЛЕНИЕ_ОТКУДА }.наречие:так{} } then -100 }
tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:МОМЕНТ_ВРЕМЕНИ }.наречие:так{} } then -100 }
tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:КРАТНОСТЬ }.наречие:так{} } then -100 }
// равнина напоминала поле битвы.
// ^^^^^^^^^^ ~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:напоминать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:напомнить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// Дети угостили белок орешками.
// УГОСТИТЬ можно КОГО-ТО
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:угостить{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:угощать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:угостить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:угощать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// хочешь кофе?
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:хотеть{}.<OBJECT>существительное:*{ падеж:род <в_класс>существительное:напиток{} } }
then 1
}
// мы встретили охотника, способного догнать и поймать кенгуру
// ^^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поймать{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ловить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// протестующие начали собираться на площади
// ^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:собираться{}.предлог:на{}.*:*{ падеж:предл } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:собраться{}.предлог:на{}.*:*{ падеж:предл } }
then 1
}
// Когда он вошел, все стаканы попадали с полки.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:падать{}.предлог:с{}.*:*{ падеж:род } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:попадать{}.предлог:с{}.*:*{ падеж:род } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:упасть{}.предлог:с{}.*:*{ падеж:род } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:свалиться{}.предлог:с{}.*:*{ падеж:род } } then 2 }
// подруга Иды не пришла на урок
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:придти{}.предлог:на{}.*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прийти{}.предлог:на{}.*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приходить{}.предлог:на{}.*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:зайти{}.предлог:на{}.*:*{ падеж:вин } } then 2 }
// Английская традиция акварели оказала сильное влияние на русских художников
// ~~~~~~~~ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оказать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оказывать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 }
// одна из женщин показалась ему знакомой.
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показаться{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// две женщины вывели из темноты раненого.
// ^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вывести{}.*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выводить{}.*:*{ падеж:вин } } then 2 }
// она часто просила меня рассказывать истории.
// ^^^^^^^^^^^^ ~~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:рассказать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:рассказывать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// Мы рассказывали о тех, кто менял мир
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:рассказывать{}.предлог:о{}.*:*{ падеж:вин } } then -10
}
// к вечеру жара спала.
// ^^^^ ~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { глагол:спать{}.<SUBJECT>НеодушОбъект } then -2 }
// Доллар снова сдает позиции
// ^^^^^ ~~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сдавать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сдать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// жена полковника смотрела им вслед
// ^^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:смотреть{}.послелог:вслед{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:посмотреть{}.послелог:вслед{} } then 2 }
// можно попытаться заменить собой стражу.
// ^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заменить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заменять{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// двое крестьян схватили за руки своего господина.
// ^^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:схватить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:хватить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// тебя вызывает начальник станции.
// ^^^^^^^^ ~~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вызывать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вызвать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// тот молча сунул ей два факела.
// ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сунуть{}.<OBJECT>*:*{ падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:совать{}.<OBJECT>*:*{ падеж:дат } } then 2 }
// Михаил зажал себе ладонью рот.
// ^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:зажать{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:зажимать{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// им оставалось преодолеть около тридцати футов.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { 'оставалось'{2 class:безлич_глагол}.<OBJECT>*:*{ 1 падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { 'остается'{2 class:безлич_глагол}.<OBJECT>*:*{ 1 падеж:дат } } then 2 }
// ей приходилось идти очень медленно.
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { 'приходилось'{ 2 class:безлич_глагол }.<OBJECT>*:*{ 1 падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { 'приходится'{2 class:безлич_глагол}.<OBJECT>*:*{ 1 падеж:дат } } then 2 }
// кого интересует мнение машины?
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:интересовать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
// Газета сообщает об открытии сессии парламента.
// ^^^^^^^^ ~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сообщать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сообщить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сообщать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сообщить{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
// ей довелось увидеть только последствия.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { 'довелось'{2}.<OBJECT>*:*{ 1 падеж:дат } } then 2 }
// Геолог недавно открыл залежи руды.
// ^^^^^^ ~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:открыть{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:открывать{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// Дети не дают матери покоя.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context {
rus_verbs:давать{}.{
частица:не{}
<OBJECT>*:*{ падеж:дат }
<OBJECT>*:*{ падеж:род }
}
} then 2
}
// Директор заявил, что уходит на пенсию.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:заявить{}.союз:что{} } then 2
}
// Люди провозгласили его гениальным писателем.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:провозгласить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:провозглашать{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// они создали магию крови.
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:создать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:создавать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// они боятся меня теперь.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:бояться{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// они называли ее железной.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:называть{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:назвать{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// он отнес коробку к дедушке
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отнести{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:относить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отнести{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:относить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// какой вес имеют эти вещи искусства?
// ^^^^^ ~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:иметь{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -100 }
// но прежде нам необходимо найти тело
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context {
безлич_глагол:необходимо{}.{
<SUBJECT>*:*{ падеж:дат }
<INFINITIVE>инфинитив:*{}
}
} then 2
}
// вы можете предоставить ему другую работу?
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предоставить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предоставлять{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предоставить{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предоставлять{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
// Никто из присутствующих при этом не пострадал.
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian { if context { местоим_сущ:никто{}.предлог:из{} } then 5 }
// она протянула к огню руки.
// ^^^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:протянуть{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:протягивать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
// почему она ему поверила?
// ^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:поверить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:верить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 }
// человек впервые показал эмоции.
// ^^^^^^^ ~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показывать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
// хочешь передать ему новость?
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:передать{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:передавать{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 }
// они зашли за угол крепости.
// ^^^^^ ~~~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:зайти{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заходить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// ты достаточно заплатил ему?
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заплатить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:платить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 }
// их тоже стало меньше?
// ^^ ^^^^^
tree_scorer language=Russian { if context { 'стало'.<OBJECT>*:*{ падеж:род } } then 1 }
tree_scorer language=Russian { if context { 'станет'.<OBJECT>*:*{ падеж:род } } then 1 }
// ему хотелось выпить все озеро.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { безлич_глагол:хочется{}.<SUBJECT>ОдушОбъект{ падеж:дат } } then 2 }
// как им хочется меня убить!
// ^^^^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { безлич_глагол:хочется{}.{ <SUBJECT>ОдушОбъект{ падеж:дат } инфинитив:*{} } }
then 2
}
// нам следует передать им это дело
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { безлич_глагол:следует{}.<SUBJECT>ОдушОбъект{ падеж:дат } } then 2 }
// все данные у него есть.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { 'есть'{ class:глагол 2 }.предлог:у{ 1 } } then 2 }
// сколько уверенности принесли они мне.
// ^^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:принести{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приносить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// возьмут ли меня туда?
// ^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:взять{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:брать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
// она обхватила его руками за шею.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обхватить{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обхватывать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
// один из гномов ткнул его палкой.
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ткнуть{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:тыкать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
// такое обращение может его сильно обидеть.
// ^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обидеть{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обижать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обидеть{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обижать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 }
// дай мне прикончить его!
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прикончить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приканчивать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// теперь она может выслушать его.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выслушать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выслушивать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// внешность этой женщины поразила его.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поразить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поражать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// ты его недавно сделал?
// ^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сделать{}.<OBJECT>местоимение:*{ падеж:вин } } then 2 }
// не смей вовлекать его в свои делишки
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вовлекать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вовлечь{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// дилер выгодно продал акции
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продавать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// мы выдали ему костюм
// --> выдать обычно можно кому-то
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдавать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдавать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдавать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
// я доверяю ему в этих вопросах
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доверять{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доверить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доверять{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доверить{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
// Она хотела побыстрее его женить
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:женить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// его избили
// --> ИЗБИТЬ КОГО-ТО
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:избить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:избивать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// собственные слова тут же показались верхом глупости.
// ПОКАЗАТЬСЯ можно КОМУ-ТО, а не ЧЕМУ-ТО
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показаться{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:казаться{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
// мы продолжали поднимать тяжести
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поднимать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
// Круче не придумаешь
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:придумать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
// Ключевая валютная пара останется волатильной
// ^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:остаться{}.прилагательное:*{ падеж:дат } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оставаться{}.прилагательное:*{ падеж:дат } } then -1 }
// остальные были заняты тем же
tree_scorer language=Russian { if context { прилагательное:занятый{ краткий }.*:*{ падеж:твор } } then 2 }
// записи мы посмотрим потом
// ^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:посмотреть{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -1
}
// целенаправленно обеспечивали его свежей продуктовой массой
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:обеспечивать{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// Олег потрогал его ногой
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:потрогать{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// хозяин пнул его ногой
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:пнуть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// Иван отодвинул его рукой
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:отодвинуть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// слуга вновь наполнил его вином
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:наполнить{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// многие горожане сочли его попыткой скрыть преступление под давлением евреев
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:счесть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// Суд признал его виновным.
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:признать{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// отец остановил ее жестом руки.
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:остановить{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// молодой человек оттолкнул его взглядом!
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:оттолкнуть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// тот ловко подхватил его левой рукой.
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:подхватить{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// младший толкнул его ногой
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:толкнуть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// капитан прикрыл ладонью глаза
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:прикрыть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// Пол удивленно поднял брови.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поднять{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -1
}
// ты должна ненавидеть ее всей душой
// ^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:ненавидеть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:попытаться{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } }
then -1
}
// кенгуру не умеет петь песни
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:петь{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -1
}
// они называли ее железной.
// ^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:называть{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
}
}
then 1
}
// Ударил ли Артур копьем дракона?
// тогда ударил ее кулаком по голове
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ударить{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
}
}
then 2
}
// УДАРИТЬ можно либо что-то, либо по чему-то:
// тот ударил по ней кулаком
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ударить{}.{
<OBJECT>*:*{ падеж:вин }
<PREPOS_ADJUNCT>предлог:по{}
}
}
then -5
}
// +++++++++++++++++++++++++++++++++++++++++++++++++=
// Самый западный и самый большой полуостров Азии - Аравийский
// ^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:самый{}.прилагательное:*{} }
then 1
}
// Даже сторонники экс-премьера не смогли поприветствовать своего кумира
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смочь{}.{
<OBJECT>*:*{ падеж:вин }
инфинитив:*{}.<OBJECT>*:*{ падеж:вин }
}
}
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смочь{}.{
<OBJECT>*:*{ падеж:род }
инфинитив:*{}.<OBJECT>*:*{ падеж:вин }
}
}
then -1
}
// ресницы ее начали опускаться
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:начать{}.{
<OBJECT>*:*{ падеж:вин }
инфинитив:*{}
}
}
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:начать{}.{
<OBJECT>*:*{ падеж:род }
инфинитив:*{}
}
}
then -1
}
// Завершаем 83-й женевский автосалон масштабным обзором новинок в лидирующих сегментах автопрома
// ^^^^^^^^^ ^^^^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:завершать{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
}
}
then 2
}
/*
// В День Воли белорусов призвали побороть страх и лень
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:призвать{}.{
ОдушОбъект{ падеж:вин }
инфинитив:*{}
}
}
then 5
}
// РФ призывает США воздержаться от линии силового давления на Дамаск.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:призывать{}.{
<OBJECT>*:*{ падеж:вин }
инфинитив:*{}
}
}
then 5
}
*/
// Он не произнёс ни слова.
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.{
частица:не{}
существительное:*{ падеж:род }.частица:ни{}
}
}
then 5
}
// США хотят нормализовать отношения с Россией
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:хотеть{}.{
<SUBJECT>*:*{}
инфинитив:*{}
}
}
then 1
}
// их стали делать
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:стать{1}.инфинитив:*{ вид:несоверш } }
then 2
}
// Понизим достоверность связывания ПООБЕЩАТЬ с дательным падежом слева, чтобы не
// возникала ошибка в предложениях типа:
// Президент Ингушетии пообещал ...
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пообещать{2}.{
<OBJECT>*:*{ 1 падеж:дат }
}
}
then -1
}
// ========================================================================
// Некоторые модальные глаголы не могут присоединять прямое дополнение в
// винительном падеже, если присоединен инфинитив:
//
// Я ничего не смог из него выжать
// ^^^^^^ ~~~~
// Я яблоко ему не смог отдать
// ^^^^^^ ~~~~
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:указать{}
}
// Попробуй ты ее успокоить
tree_scorer ВалентностьГлагола language=Russian
{
if context { МодальнБезДоп.{ <OBJECT>*:*{ падеж:вин } инфинитив:*{} } }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { МодальнБезДоп.{ <OBJECT>*:*{ падеж:род } инфинитив:*{} } }
then -100
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.<LEFT_AUX_VERB>МодальнБезДоп.<OBJECT>*:*{ падеж:вин } }
then -100
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.<LEFT_AUX_VERB>МодальнБезДоп.<OBJECT>*:*{ падеж:род } }
then -100
}
// ========================================================================
// ===========================================================================================
// Некоторые модальные глаголы обычно требуют присоединения и прямого дополнения, и инфинитива
// ===========================================================================================
#define МодальнСВинДоп(v) \
#begin
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{3 }.{ <OBJECT>*:*{ падеж:вин 2 } rus_verbs:v{1} } }
then 4
}
#end
МодальнСВинДоп(заставить) // путь заставит тебя принять это
МодальнСВинДоп(заставлять) // оно заставляет меня вспоминать
МодальнСВинДоп(выучить) // Он выучил меня играть в шахматы.
МодальнСВинДоп(учить)
МодальнСВинДоп(научить)
МодальнСВинДоп(попросить)
МодальнСВинДоп(просить)
МодальнСВинДоп(умолять)
МодальнСВинДоп(упрашивать)
МодальнСВинДоп(упросить)
// ==========================================================
// или научились ей пользоваться
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:научиться{}.{
<OBJECT>*:*{}
инфинитив:*{}
}
}
then -10
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:научиться{}.{
<OBJECT>*:*{}
инфинитив:*{}
}
}
then -10
}
// Чтобы причастие или прилагательное, прикрепленное к БЫТЬ,
// было согласовано с подлежащим по роду:
//
// а сегодняшний день обещал быть именно таким
// лето должно быть именно таким
/*
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { *:*{ модальный }.{
<SUBJECT>*:*{ род:муж число:ед }
инфинитив:быть{}.прилагательное:*{ род:муж число:ед }
} }
then 1
}
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { *:*{ модальный }.{
<SUBJECT>*:*{ род:ср число:ед }
инфинитив:быть{}.прилагательное:*{ род:ср число:ед }
} }
then 1
}
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { *:*{ модальный }.{
<SUBJECT>*:*{ род:жен число:ед }
инфинитив:быть{}.прилагательное:*{ род:жен число:ед }
} }
then 1
}
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { *:*{ модальный }.{
<SUBJECT>*:*{ число:мн }
инфинитив:быть{}.прилагательное:*{ число:мн }
} }
then 1
}
*/
// --------------------------------------------------
// подавляем присоединение одновременно прямого дополнения и инфинитива:
// Я ХОЧУ ЭТО СДЕЛАТЬ
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:хотеть{}.{
инфинитив:*{}
<OBJECT>*:*{ падеж:вин }
}
}
then -100
}
// приказывать секретарше принести кофе
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приказывать{}.{
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
// руководитель приказал пилоту начать снижение
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приказать{}.{
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 10
}
// посоветовал ему купить лопату
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:посоветовать{}.{
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 10
}
// позволять другим найти ход
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:позволять{}.{
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
// позволить компьютеру найти решение
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:позволять{}.{
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
// лицо незнакомца было покрыто потом
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:покрытый{}.<OBJECT>НеодушОбъект{ падеж:твор } }
then 2
}
// Но последний -- тот, кого называли Табююзом -- прошел через врата на Землю.
// ^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:называть{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
}
}
then 2
}
// В рядах оппозиции нашли «агентов Кремля»
// На обломках метеорита нашли скрюченных пришельцев
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.<OBJECT>ОдушОбъект{ падеж:род } }
then -10
}
// их нашли уже через час
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.<OBJECT>местоимение:я{ падеж:род } }
then -10
}
// Российские ученые нашли челюсти чудовища на дне ледяного озера
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.<OBJECT>НеодушОбъект{ падеж:род } }
then -1
}
// скоро она начнет искать меня
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:искать{}.<OBJECT>ОдушОбъект{ падеж:род } }
then -10
}
// мне придется искать помощи
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:искать{}.<OBJECT>НеодушОбъект{ падеж:род } }
then -2
}
// родителям пришлось искать его в одной из соседних станиц
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:искать{}.<OBJECT>местоимение:*{ падеж:род } }
then -10
}
// Подавим появление императива для НАСЛАТЬ, когда к нему прикреплен В+предл
// В рядах оппозиции нашли «агентов Кремля»
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:наслать{ наклонение:побуд }.предлог:в{}.*:*{ падеж:предл } } then -10 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:наслать{ наклонение:побуд }.предлог:на{}.*:*{ падеж:предл } } then -10 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:наслать{ наклонение:побуд }.предлог:у{} } then -10 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:наслать{ наклонение:побуд }.предлог:под{} } then -10 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:наслать{ наклонение:побуд }.предлог:над{} } then -10 }
// ИНТЕРЕСОВАТЬ - обычно кого-то, а не что-то
// Наравне с литературой его интересует и живопись.
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:интересовать{}.<OBJECT>НеодушОбъект } then -2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:интересовать{}.<OBJECT>ОдушОбъект{ падеж:род } } then -10 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:интересовать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
// Модальный ХОТЕТЬ, присоединив инфинитив, уже не может
// присоединять некоторые предложные дополнения:
// она хотела освободиться от меня
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:хотеть{}.{
<INFINITIVE>*:*{}
предлог:от{} }
}
then -100
}
// Обычно КОМУ-ТО идет ОДЕЖДА.
// по всему берегу шла работа
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:идти{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -10 }
// Подавим присоединение наречия КАК справа к БЫТЬ:
// это было как волшебство
// ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:быть{1}.наречие:как{2} } then -10 }
// Для ПАХНУТЬ - либо ОТ+род, либо КТО-ТО.
// а от вас слишком уж пахнет
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:пахнуть{ вид:несоверш }.{
<SUBJECT>*:*{}
предлог:от{}
}
}
then -100
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:пахнуть{ вид:соверш }.{
<SUBJECT>*:*{}
предлог:от{}
}
}
then -100
}
// Обычно время суток не может являться именным сказуемым (вместе со связкой)
// где ж ты был прошлой ночью?
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:быть{}.<RHEMA>ЧастьСуток{ ПАДЕЖ:ТВОР } }
then -2
}
// обычно ГОВОРЯТ КОМУ-ТО:
// пару минут пытался говорить.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:говорить{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -2
}
// вещи мы забрали без шума
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:забрать{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -10
}
// их кони шли легким шагом
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:идти{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -10
}
// послушай лучше меня!
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:послушать{ наклонение:побуд }.{
<ATTRIBUTE>'лучше'{ class:наречие }
<OBJECT>*:*{ ПАДЕЖ:ВИН }
}
}
then 5
}
// нет больше вашего дракона
tree_scorer language=Russian
{
if context { частица:нет{}.{
<ATTRIBUTE>'больше'{ class:наречие }
существительное:*{ падеж:род }
}
}
then 5
}
// обычно КЕМ-ТО не едят:
// Антонио ел пюре каждый день
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:есть{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ТВОР } }
then -10
}
// только как это сделать?
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сделать{}.{
<ATTRIBUTE>наречие:как{}.[not]*:*{}
<OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН }
} }
then 1
}
// Мозг этих существ сходен по размерам с мозгом динозавра
// ^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:сходный{}.предлог:с{}.*:*{ падеж:твор } }
then 2
}
// Я пришёл сюда раньше его
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:придти{}.предлог:раньше{}.*:*{ падеж:род } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:прийти{}.предлог:раньше{}.*:*{ падеж:род } }
then 2
}
// В США миллионера осудили за попытку продать Ирану детали для ракет ПВО
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:продать{}.{
<OBJECT>*:*{ падеж:дат }
<OBJECT>*:*{ падеж:вин }
} }
then 2
}
// ты можешь отдать его своему другу.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отдать{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:дат }
} }
then 2
}
// тратить время на пустяки
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:тратить{}.{
<OBJECT>НеодушОбъект{ падеж:вин }
предлог.*:*{ падеж:вин }
} }
then 2
}
// а каким же образом о нем узнали вы?
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:узнать{}.предлог:о{}.*:*{ падеж:предл } }
then 2
}
// еще четверо тащили под руки своих раненых
// ^^^^^^ ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:тащить{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// некоторые из них тащили за собой платформы
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:тащить{}.{
предлог:из{}
предлог:за{}
} }
then -10
}
// ты можешь узнать подробности у нее
// Узнав его, они закричали
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:узнать{}.<OBJECT>*:*{ падеж:род } }
then -1
}
// мне бы хотелось узнать о судьбе своего кота.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:узнать{}.{
предлог:о{}
<OBJECT>ОдушОбъект{ падеж:вин }
} }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:узнать{}.{
предлог:об{}
<OBJECT>ОдушОбъект{ падеж:вин }
} }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.{
предлог:о{}
<OBJECT>ОдушОбъект{ падеж:вин }
} }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.{
предлог:об{}
<OBJECT>ОдушОбъект{ падеж:вин }
} }
then -100
}
// меня называли прекрасным человеком
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:называть{}.{
<OBJECT>*:*{ падеж:дат }
<OBJECT>*:*{ падеж:твор }
} }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:назвать{}.{
<OBJECT>*:*{ падеж:дат }
<OBJECT>*:*{ падеж:твор }
} }
then -100
}
// Мы выбрали его секретарём нашей организации.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:выбрать{}.{
<OBJECT>ОдушОбъект{ падеж:вин }
<OBJECT>ОдушОбъект{ падеж:твор }
} }
then 2
}
// отдал бы пару лет жизни
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:узнать{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -1
}
// Предпочитаем одушевленный объект в конструкции:
//
// Узнать от соседей
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:узнать{}.<PREPOS_ADJUNCT>предлог:от{}.<OBJECT>НеодушОбъект{ падеж:род } }
then -2
}
// Общее правило для побудительного наклонения: явный субъект не
// может быть в "сослагательном наклонении", то есть иметь частицу БЫ:
//
// меня бы непременно нашли
// ^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ наклонение:побуд }.<SUBJECT>*:*{}.частица:бы{} }
then -100
}
// -----------------------------------------------------------------
// Некоторые наречия не сочетаются с императивом, и это позволяет
// снимать омонимию:
//
// где мой револьвер?
// ^^^ ~~~
wordentry_set СловаНеДляИмператива=
{
наречие:где{},
наречие:когда{},
наречие:почему{},
наречие:зачем{},
наречие:отчего{},
местоим_сущ:кто{},
местоим_сущ:кто-то{},
местоим_сущ:что{},
местоим_сущ:что-то{}
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ наклонение:побуд }.СловаНеДляИмператива }
then -10
}
// -----------------------------------------------------------------
// она ждала от него совсем другого
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ждать{}.наречие:совсем{} }
then -100
}
// теперь было совсем другое дело
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:быть{}.наречие:совсем{} }
then -100
}
// она могла вполне оказаться правой
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оказаться{}.наречие:вполне{} }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оказаться{}.наречие:совсем{} }
then -100
}
// Для отрицательной формы переходного глагола
// подавим родительный падеж для прямого одушевленного дополнения:
// Самого богатого француза не пустили в Бельгию
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ ПАДЕЖ:ВИН }.{
частица:не{}
<OBJECT>ОдушОбъект{ ПАДЕЖ:РОД }
} }
then -2
}
// Придавим вариант прошедшего времени для несовершенного глагола, если
// есть наречие настоящего или будущего времени:
// уж больно ты сейчас слаб
// ^^^^^^^^^^^
wordentry_set НаречиеНастБуд=наречие:{ сейчас, завтра, послезавтра }
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:слабнуть{ ВРЕМЯ:ПРОШЕДШЕЕ }.{
НаречиеНастБуд
} }
then -1
}
// Подавляем наречие ДОСТАТОЧНО справа от БЫТЬ:
// она была достаточно влажной
// есть достаточно благополучные северные территории
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:быть{}.наречие:достаточно{} }
then -10
}
// нам всем очень жаль тебя
tree_scorer ВалентностьГлагола language=Russian
{
if context { безлич_глагол:жаль{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:РОД } }
then -2
}
// извивалась под его длинными усами
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:извиваться{}.предлог:под{}.*:*{ падеж:вин } }
then -100
}
// а результаты могли быть куда хуже
// ^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:мочь{1}.наречие:куда{2} }
then -2
}
// модальный глагол МОЧЬ обычно не присоединяет предложное дополнение:
// мы можем без купюр поговорить
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:мочь{}.предлог:*{} }
then -1
}
// когда мне смотреть новости?
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смотреть{}.<OBJECT>существительное:*{ падеж:дат одуш:неодуш } }
then -2
}
// знаешь холм позади лагеря?
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.предлог:позади{} }
then -2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.предлог:впереди{} }
then -2
}
// шли вчера по тропинке
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { 'шли'{ наклонение:побуд }.наречие:вчера{} }
then -2
}
// кругом была полная тишина
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context {
глагол:быть{1}.
{
прилагательное:*{ ~краткий падеж:им 2 }
существительное:*{ падеж:им 3 }
}
}
then -10
}
// Если ПОДОШЕЛ кому-то, то запрещаем предложное дополнение "К ЧЕМУ-ТО"
// Вольф широким шагом подошел к ним
tree_scorer ВалентностьГлагола language=Russian
{
if context {
rus_verbs:подойти{}.
{
<OBJECT>*:*{ ПАДЕЖ:ДАТ }
предлог:к{}
}
}
then -100
}
/*
// ------------------------------------------
// некоторые связочные глаголы требуют, чтобы объект был согласован с
// подлежащим по роду и числу:
// Он оказался сломанным
#define СвязочнГлагол(v) \
#begin
tree_scorer ВалентностьГлагола language=Russian
{
if context {
глагол:v{}.
{
sbj=<SUBJECT>*:*{}
obj=<OBJECT>прилагательное:*{ падеж:твор }
}
}
//constraints { НесогласСущПрил(sbj,obj) }
//constraints { sbj:РОД!=obj:РОД }
then -100
}
#end
СвязочнГлагол(оказаться)
оставаться
остаться
оказываться
стать
становиться
притворяться
притвориться
прикинуться
прикидываться
*/
// а результаты могли быть куда хуже
// ^^^^ ~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:быть{}.наречие:куда{} }
then -2
}
// ОКАЗАТЬСЯ надо подавлять справа любые наречия, кроме ГДЕ и КОГДА:
//
// Засада оказалась наполовину успешной
//
// все оказалось гораздо хуже
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оказаться{1}.наречие:*{ 2 ~ОБСТ_ВАЛ:МЕСТО ~ОБСТ_ВАЛ:МОМЕНТ_ВРЕМЕНИ ~СТЕПЕНЬ:СРАВН } }
then -2
}
// объединение их в единую работающую систему составляет сверхзадачу построения искусственного интеллекта.
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:составлять{}.{
предлог:в{}.*:*{ падеж:вин }
<OBJECT>*:*{ падеж:вин }
} }
then -2
}
wordentry_set ПритяжМестТворЗапрет=притяж_частица:{ ее, его, их }
// прилагательные ЕЁ, ЕГО, ИХ обычно не употребляются в качестве дополнения
// творительного падежа:
// силы явно оставляли ее
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{}.<OBJECT>ПритяжМестТворЗапрет }
then -5
}
// вы же ее давно знаете!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.<OBJECT>местоимение:я{ падеж:род } }
then -2
}
// вы делаете из мухи слона
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:делать{1}.{
предлог:из{2}
<OBJECT>*:*{ 3 падеж:вин }
} }
then 1
}
// Британец, спасший от акулы детей в Австралии, потерял работу (СПАСШИЙ ОТ КОГО-ТО КОГО-ТО)
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:спасти{1}.{
предлог:от{2}
<OBJECT>*:*{ 3 падеж:вин }
} }
then 1
}
// небольшой штраф за родительное дополнение:
// мы оба знали правила игры.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.<OBJECT>*:*{ падеж:род } }
then -1
}
// Придаточное ", ЧТО ..." конкурирует за ту же валентность, что и прямое винительное/родительное
// дополнение, поэтому гасим одновременное наличие.
// Маленький квадратик на линии между блоком оценки награды и блоком выбора действия показывает, что эта связь модулирует значимость действия
// ~~~~~~~~ ^^^^^^^^^^^^^^^^
tree_scorers ВинРодДопГл
tree_scorer ВинРодДопГл language=Russian { if context { *:*{ падеж:вин } } then 1 }
tree_scorer ВинРодДопГл language=Russian { if context { *:*{ падеж:род } } then 1 }
tree_scorer ВалентностьСложнСказ language=Russian generic
{
if context { *:*{}.{
<OBJECT>ВинРодДопГл
<NEXT_CLAUSE>','.союз:что{}
}
}
then -5
}
wordentry_set Прелог_О_Об={ предлог:о{}, предлог:об{} }
// Универсальный принцип: косвенное дополнение О+чем-то заполняет тот же слот, что
// и вин/род дополнение:
// О появлении свежей лавы свидетельствует мощная подсветка в вершинном кратере вулкана
// ^^^^^^^^^^^ ~~~~~~~~~~~
tree_scorer ВалентностьСложнСказ language=Russian generic
{
if context { *:*{}.{
<OBJECT>ВинРодДопГл
Прелог_О_Об.*:*{ падеж:предл }
}
}
then -10
}
// их даже стали из бумаги делать
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { rus_verbs:делать{}.{
<OBJECT>ВинРодДопГл
предлог:из{}
}
}
then 1
}
// только пустое пространство - космос
tree_scorer ВалентностьСложнСказ language=Russian generic
{
if context { '-'.<ATTRIBUTE>наречие:только{} }
then -2
}
// Подавим присоединение одушевленного родительного дополнения
// к глаголам в случае, если глагол может присоединить винительное:
// Я хочу тебя
// ^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{ переходность:переходный падеж:вин падеж:род }.
ОдушОбъект{ падеж:род }
}
then -1
}
// Дмитрий сказал ей об этом
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сказать{}.<OBJECT>местоимение:я{ падеж:твор } }
then -2
}
// пожелать спортсменам удачи
// ^^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пожелать{}.<OBJECT>*:*{ падеж:род одуш:неодуш } }
then 1
}
// пожелать спортсменам удачи
// ^^^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пожелать{}.<OBJECT>*:*{ падеж:дат одуш:одуш } }
then 1
}
// желать спортсменам удачи
// ^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:желать{}.<OBJECT>*:*{ падеж:род одуш:неодуш } }
then 1
}
// желать спортсменам удачи
// ^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:желать{}.<OBJECT>*:*{ падеж:дат одуш:одуш } }
then 1
}
// Мама налила чай
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:налить{}.<OBJECT>существительное:*{ падеж:вин <в_класс>существительное:напиток{} } }
then 1
}
// Оля съела пюре
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:съесть{}.<OBJECT>существительное:*{ падеж:вин <в_класс>существительное:еда{} } }
then 1
}
// испросить разрешения
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:испросить{}.<OBJECT>*:*{ падеж:род одуш:неодуш } }
then 3
}
// наделать в решении ошибок
// ^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:наделать{}.<OBJECT>существительное:*{ падеж:род } }
then 2
}
// дракон смотрит вслед человеку.
// ^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смотреть{}.предлог:вслед{}.*:*{ падеж:дат } }
then 1
}
// нажимать на все кнопки
// ^^^^^^^^ ^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:нажимать{}.предлог:на{}.существительное:*{ одуш:неодуш падеж:вин } }
then 1
}
// предикатив МОЖНО обычно присоединяет только одушевленный дательный агенс:
// на этой удивительно четкой фотографии можно увидеть рассеянное скопление
// ~~~~~~~~~~ ^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:можно{}.<SUBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -2
}
// поэтому - очень легкий спуск
tree_scorer ВалентностьПредиката language=Russian
{
if context { '-'.<ATTRIBUTE>наречие:очень{} }
then -10
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { '–'.<ATTRIBUTE>наречие:очень{} }
then -10
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { '—'.<ATTRIBUTE>наречие:очень{} }
then -10
}
// Мужчина, взявший в заложники пожарных в США, убит при штурме
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { rus_verbs:взять{}.{
<OBJECT>*:*{ падеж:вин }
предлог:в{}.*:*{ падеж:им }
}
}
then 2
}
// отчего же получается такая разница?
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { глагол:получаться{1}.{
прилагательное:*{2 падеж:им }
<SUBJECT>*:*{ 3 }
}
}
then -2
}
// отчего же получилась такая разница?
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { глагол:получиться{1}.{
прилагательное:*{2 падеж:им }
<SUBJECT>*:*{ 3 }
}
}
then -2
}
// черный кожаный костюм делал его почти невидимым
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { rus_verbs:делать{}.{
<OBJECT>*:*{ падеж:вин }
прилагательное:*{ падеж:твор }
}
}
then 1
}
// Общее правило для глаголов - два наречия подряд прикрепляются
// достаточно редко.
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.@sequence_pos(НАРЕЧИЕ) }
then -1
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.@sequence_pos(НАРЕЧИЕ) }
then -1
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { деепричастие:*{}.@sequence_pos(НАРЕЧИЕ) }
then -1
}
// как это все объяснить?
// ^^^^^^^^^^^
tree_scorer language=Russian generic
{
if context { наречие:как{1}.местоим_сущ:все{} }
then -1
}
tree_scorer language=Russian
{
if context { наречие:как{1}.местоим_сущ:это{} }
then -1
}
// *******************************************************************************
// Подавляем одновременное присоединение винительного и родительного дополнения
//
// я буду ждать результаты проверки
// ^^^^^^^^^^^^^^^^^^^^^^^^^
// *******************************************************************************
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:род }
}
}
then -10
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:парт }
}
}
then -10
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{}.{
<OBJECT>*:*{ падеж:род }
<OBJECT>*:*{ падеж:парт }
}
}
then -10
}
// ------------------------------------------------------
// Немного придавим использование прилагательного в роли
// творительного дополнения:
// нога жреца коснулась первой ступеньки.
// ^^^^^^
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:сделаться{}
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{ ~ГлаголыСвязки }.<OBJECT>прилагательное:*{ падеж:твор } }
then -2
}
// Желать вам всем удачи
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{ ~ГлаголыСвязки }.<OBJECT>местоим_сущ:всё{ падеж:твор } }
then -2
}
// ------------------------------------------------------
// забористый бас Константина делал его легко узнаваемым
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:делать{}.<OBJECT>прилагательное:*{ падеж:дат }
}
then -2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сделать{}.<OBJECT>прилагательное:*{ падеж:дат }
}
then -2
}
// ------------------------------------------------------
// злодей схватил нож и несколько раз всадил его оппоненту в спину
// ^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:всадить{}.{
<OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН}
<OBJECT>*:*{ ПАДЕЖ:ДАТ }
}
}
then 1
}
// ------------------------------------------------------
// Обычно глагол не может одновременно присоединять и винительный,
// и родительный падеж, но некоторые глаголы - могут:
// это может лишить наше общество работы
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:лишить{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД }
}
}
then 12
}
// ------------------------------------------------------
// она обхватила его руками за шею
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обхватить{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
}
then 1
}
// ------------------------------------------------------
// Подавляем для модального ХОТЕТЬ присоединение дополнений,
// когда присоединен инфинитив:
// ты это хотел мне рассказать?
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:хотеть{}.{ <OBJECT>*:*{ падеж:дат } инфинитив:*{} } } then -10 }
// ------------------------------------------------------
// Однако их ярость уступила место страху
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { rus_verbs:уступить{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:дат }
}
}
then 1
}
// --------------------------------------------------------------
// глагол ПОМОЧЬ обычно присоединяет дательную валентность.
// мне надо им помочь
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:помочь{}.[not]<OBJECT>*:*{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:помогать{}.[not]<OBJECT>*:*{ падеж:дат } } then -2 }
// -------------------------------
// злодей схватил нож и несколько раз всадил его оппоненту в спину
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { rus_verbs:всадить{}.{
<OBJECT>НеодушОбъект{ падеж:вин }
<OBJECT>ОдушОбъект{ падеж:дат }
}
}
then 1
}
// ------------------------------------
// за деревьями леса не видеть
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:видеть{}.{
частица:не{}
<OBJECT>*:*{ падеж:род }
}
}
then 1
}
// ------------------------------------
// Подавляем компаратив наречия справа от ОКАЗАТЬСЯ, если
// у глагола есть прямое дополнение:
// эта задача оказалась гораздо легче первой.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оказаться{}.{
наречие:*{ степень:сравн }
*:*{ падеж:твор }
}
}
then -10
}
// ----------------------------------------------
// Обычно рассказывают либо ЧТО-ТО, либо о ЧЕМ-ТО
// Набив рот, он попросил ее рассказать о вторжении.
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:рассказать{}.{
*:*{ падеж:вин }
предлог:о{}
}
}
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:рассказать{}.{
*:*{ падеж:род }
предлог:о{}
}
}
then -5
}
// Набив рот, он попросил ее рассказать о вторжении.
// ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:попросить{}.{
инфинитив:*{}
предлог:о{}
}
}
then -5
}
// Предприниматели ФРГ выступают за добычу сланцевого газа
// ^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:выступать{2}.<OBJECT>*:*{ 1 падеж:твор } } then -2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:выступать{}.<OBJECT>*:*{ падеж:твор <в_класс>существительное:страна{} } } then -2 }
// Обычно ВОСПОЛЬЗОВАТЬСЯ имеет заполненный слот творительного дополнения:
// этим мгновением надо было воспользоваться
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:воспользоваться{}.<OBJECT>*:*{ падеж:твор } } then 2 }
// откуда ее черт принес?
// Откуда её ветер принёс?
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:принести{}.{
<SUBJECT>*:*{}
<OBJECT>*:*{ падеж:вин }
}
}
then 1
}
// ей доводилось встречать эти существа
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:доводилось{}.{
<SUBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 3
}
// Есть у нас в лесу место
tree_scorer ВалентностьГлагола language=Russian
{
if context { 'есть'{ class:инфинитив }.предлог:у{} }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:заняться{}.<OBJECT>*:*{ падеж:твор } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:заниматься{}.<OBJECT>*:*{ падеж:твор } }
then 1
}
// Майкл способен попасть в кольцо с десятиметровой дистанции пять раз подряд
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:попасть{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:попадать{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 }
// Я спустил собаку с цепи.
// ^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:спустить{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:спускать{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 }
// Гоша опустил ногу со стола.
// ^^^^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:опустить{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:опускать{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 }
// тебе доводилось использовать силы магии против другого человека?
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:использовать{ вид:соверш }.предлог:против{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:использовать{ вид:несоверш }.предлог:против{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { инфинитив:использовать{ вид:соверш }.предлог:против{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { инфинитив:использовать{ вид:несоверш }.предлог:против{} } then 2 }
// лесом от него пахло
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:пахнуть{ вид:несоверш }.предлог:от{} }
then 2
}
// Дождь должен смыть всю пыль с листьев.
// ^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:смыть{}.предлог:с{}.*:*{ падеж:род} } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:смывать{}.предлог:с{}.*:*{ падеж:род} } then 2 }
// он смел крошки со стола
// ^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:смести{}.предлог:с{}.*:*{ падеж:род} } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:сметать{}.предлог:с{}.*:*{ падеж:род} } then 2 }
// Мальчики съехали на санках с горы.
// ^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:съехать{}.предлог:с{}.*:*{ падеж:род } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:съезжать{}.предлог:с{}.*:*{ падеж:род } } then 2 }
// Дети бросались в воду с моста
// ^^^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:броситься{}.предлог:с{}.*:*{ падеж:род } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:бросаться{}.предлог:с{}.*:*{ падеж:род } } then 2 }
// отнестись к животным с сочуствием
// ^^^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:отнестись{}.предлог:с{}.*:*{ падеж:твор } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:относиться{}.предлог:с{}.*:*{ падеж:твор } } then 2 }
// Элис разинула от удивления рот.
// ^^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:разинуть{}.НеодушОбъект{ падеж:вин } } then 2 }
// --------------------------------------
// ВЛЮБЛЯТЬСЯ В КОГО-ТО
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:влюбляться{}.предлог:в{}.*:*{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:влюбляться{}.предлог:в{}.существительное:*{ одуш:одуш падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:влюбляться{}.предлог:в{}.существительное:*{ падеж:вин <в_класс>существительное:имя{} } } then 3 }
// --------------------------------------
// ВЛЮБИТЬСЯ В КОГО-ТО
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:влюбиться{}.предлог:в{}.*:*{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:влюбиться{}.предлог:в{}.существительное:*{ одуш:одуш падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:влюбиться{}.предлог:в{}.существительное:*{ падеж:вин <в_класс>существительное:имя{} } } then 3 }
// --------------------------------------
// ВТЮРИТЬСЯ В КОГО-ТО
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:втюриться{}.предлог:в{}.*:*{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:втюриться{}.предлог:в{}.существительное:*{ одуш:одуш падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:втюриться{}.предлог:в{}.существительное:*{ падеж:вин <в_класс>существительное:имя{} } } then 3 }
// ------------------------------------------------
// **** Глаголы перемещения с топонимами ****
tree_scorers ЛюбойТопонимНеизв
// для неизвестных топонимов
tree_scorer ЛюбойТопонимНеизв language=Russian
{
if context { существительное:???{ charcasing:FirstCapitalized } }
then 1
}
tree_scorer ЛюбойТопонимНеизв language=Russian
{
if context { существительное:*{ <в_класс>существительное:страна{} } }
then 1
}
tree_scorer ЛюбойТопонимНеизв language=Russian
{
if context { существительное:*{ <в_класс>существительное:город{} } }
then 1
}
// +++++
// для слов типа ТАКСИ
tree_scorers ЛюбойТранспорт
tree_scorer ЛюбойТранспорт language=Russian
{
if context { существительное:*{ <в_класс>существительное:транспорт{} } }
then 1
}
// +++++
tree_scorers ЛюбойЧеловек
tree_scorer ЛюбойЧеловек language=Russian
{
if context { существительное:*{ <в_класс>существительное:профессия{} } }
then 1
}
tree_scorer ЛюбойЧеловек language=Russian
{
if context { существительное:*{ <в_класс>существительное:имя{} } }
then 1
}
// +++++
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:улететь{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:улететь{}.предлог:в{}.ЛюбойТранспорт{ падеж:предл } } then 2 }
// ++++
// он уехал в Токио
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:уехать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// он уехал в такси
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:уехать{}.предлог:в{}.ЛюбойТранспорт{ падеж:предл } } then 2 }
// ++++
// Мы эмигрировали в США
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:эмигрировать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// ++++
// Виктор перебрался в Токио
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:перебраться{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// ++++
// Мафиози сбежали из Токио
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:сбежать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// ++++
// Они едут в Токио
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:ехать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// мы ехали в такси
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:ехать{}.предлог:в{}.ЛюбойТранспорт{ падеж:предл } } then 2 }
// ++++
// туристы поехали в Киото
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:поехать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:поехать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:предл } } then -10 }
// группа туристов поехала в такси
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:поехать{}.предлог:в{}.ЛюбойТранспорт{ падеж:предл } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:поехать{}.предлог:в{}.ЛюбойТранспорт{ падеж:вин } } then -10 }
// ++++
// Люси отправилась в Токио
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:отправиться{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// ++++
// Мы посетили Киото
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:посетить{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// ++++
// путешественники посещали Киото
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:посещать{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// ++++
// Мы спросили Людмилу Ивановну
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:спросить{}.ЛюбойЧеловек{ падеж:вин } } then 2 }
// Дети спросили совет у учителя
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:спросить{}.предлог:у{}.ЛюбойЧеловек{ падеж:род } } then 2 }
// ++++
// Дети спрашивают медсестру
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:спрашивать{}.ЛюбойЧеловек{ падеж:вин } } then 2 }
// Дети спрашивают совет у учителя
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:спрашивать{}.предлог:у{}.ЛюбойЧеловек{ падеж:род } } then 2 }
// ++++
// мы поинтересовались ответом у учительницы
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:поинтересоваться{}.предлог:у{}.ЛюбойЧеловек{ падеж:род } } then 2 }
// ++++
// Вдалеке мы увидели Токио
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:увидеть{}.*:*{ падеж:вин } } then 1 }
// ++++
// Справа вы видите Киото
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:видеть{}.*:*{ падеж:вин } } then 1 }
// ++++
//
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:построить{}.НеодушОбъект{ падеж:вин } } then 1 }
// ++++
//
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:строить{}.НеодушОбъект{ падеж:вин } } then 1 }
// ++++
//
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:создать{}.НеодушОбъект{ падеж:вин } } then 1 }
// ++++
//
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:создавать{}.НеодушОбъект{ падеж:вин } } then 1 }
// ++++
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:обмениваться{}.*:*{ падеж:твор } } then 1 }
// ++++
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:обменяться{}.*:*{ падеж:твор } } then 1 }
// +++++
// Элис разинула от удивления рот.
// ^^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:разинуть{}.НеодушОбъект{ падеж:вин } } then 1 }
// ++++++
// Я покажу тебе, как надо мной смеяться!
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смеяться{}.местоимение:*{ падеж:твор } }
then -5
}
// ++++++++++
// плыть ей пришлось долго.
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:пришлось{}.{
<SUBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:плыть{}.местоимение:*{ падеж:твор } }
then -5
}
// ++++++++++
// все остальное тебе тоже удалось устроить?
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:удалось{}.{
<SUBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
// +++++++++++++++
// Это событие является одним из элементов широко задуманной акции.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:являться{}.'одним'{ падеж:твор }.'из' }
then 2
}
// +++++++++++++++
// вот кого мне нужно было искать!
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:нужно{}.{
<SUBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
// +++++++++++++++++
// им надо видеть движение.
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:надо{}.{
<SUBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
// +++++++++++++++++
// но прежде нам необходимо найти тело
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:необходимо{2}.{
<SUBJECT>*:*{ падеж:дат 1 }
инфинитив:*{3}
}
}
then 4
}
// +++++++++++++++++
// мимо тебя пройти невозможно
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:пройти{}.{
наречие:мимо{}
<OBJECT>*:*{ падеж:вин }
}
}
then -10
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:пройти{}.{
наречие:мимо{}
<OBJECT>*:*{ падеж:род }
}
}
then -10
}
// +++++++++++++++++
// Сегодня я буду читать дома
// ^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:читать{}.{
<OBJECT>существительное:*{ <в_класс> СУЩЕСТВИТЕЛЬНОЕ:СТРОЕНИЕ{} }
}
}
then -10
}
// +++++++++++++++++
// Она ослепила его своей красотой.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:ослепить{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
}
}
then 2
}
// +++++++++++++++++++
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:слышать{}.<OBJECT>существительное:*{ <в_класс>существительное:звук{} } }
then 2
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:слышать{}.<SUBJECT>существительное:*{ <в_класс>существительное:звук{} } }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:услышать{}.<OBJECT>существительное:*{ <в_класс>существительное:звук{} } }
then 2
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:услышать{}.<SUBJECT>существительное:*{ <в_класс>существительное:звук{} } }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:расслышать{}.<OBJECT>существительное:*{ <в_класс>существительное:звук{} } }
then 2
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:расслышать{}.<SUBJECT>существительное:*{ <в_класс>существительное:звук{} } }
then -5
}
// +++++++++++++++++++++++++
/*
// пища помогла мне окончательно прогнать сон
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:помочь{}.{
<SUBJECT>*:*{}
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 5
}
*/
// +++++++++++++++++
// Немного повысим достоверность императива в случае,
// когда предложение оканчивается восклицательным знаком:
// держите ее за ноги!
tree_scorer language=Russian
{
if context { глагол:*{ наклонение:побуд }.'!' }
then 1
}
// - А яичницу любите?
tree_scorer language=Russian
{
if context { глагол:*{ наклонение:побуд }.'?' }
then -4
}
// +++++++++++++++++
// Страх охватил Грегори
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:охватить{}.{
<SUBJECT>существительное:*{ одуш:неодуш <в_класс>существительное:эмоция{} }
<OBJECT>*:*{ падеж:вин }
}
}
then 5
}
// ++++++++++++++++++
// какие тут могут быть секреты?
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:мочь{}.{
инфинитив:*{}
<OBJECT>*:*{ падеж:вин }
}
}
then -100
}
// +++++++++++++++++
// В Ульяновской области детей обстреляли из пневматики
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обстрелять{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// +++++++++++++++++
// теперь вы все знаете
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.<OBJECT>'все'{ падеж:вин } }
then 2
}
// +++++++++++++++++
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:предложить{}.{ <OBJECT>*:*{ падеж:дат } инфинитив:*{} } }
then 6
}
// +++++++++++++++++
// Мы велели ей убраться из комнаты
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:велеть{}.{ <OBJECT>*:*{ падеж:дат } инфинитив:*{} } }
then 6
}
// +++++++++++++++++
// Обычно глагол БЫТЬ не присоединяет прямое дополнение в винительном падеже:
// Это будет аварийный запас.
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.<OBJECT>*:*{ падеж:вин } }
then -5
}
// в этом кафе будут они
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:быть{}.{
<SUBJECT>местоимение:*{ падеж:им }
<RHEMA>*:*{ одуш:неодуш падеж:им }
}
}
then -3
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:быть{}.{
<RHEMA>местоимение:*{ падеж:им }
<SUBJECT>существительное:*{ одуш:неодуш падеж:им }
}
}
then -3
}
// Компаратив наречия для БЫТЬ/БЫВАТЬ подавляем
// она была старше меня
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.<RHEMA>наречие:*{ степень:сравн } }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:бывать{}.<RHEMA>наречие:*{ степень:сравн } }
then -5
}
// +++++++++++++++++
// Глаголы, синонимичные ЗАПЕРЕТЬ - подавляем вариант, когда подлежащим становится
// существительное из класса ЗДАНИЕ:
// запер сарай
// ^^^^^^^^^^^^
#define ЗаперетьЗдание(v) \
#begin
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:v{}.<SUBJECT>существительное:*{ <в_класс>существительное:здание{} } }
then -100
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:v{}.<SUBJECT>существительное:*{ <в_класс>существительное:здание{} } }
then -100
}
#end
ЗаперетьЗдание(запереть)
ЗаперетьЗдание(запирать)
ЗаперетьЗдание(закрыть)
ЗаперетьЗдание(закрывать)
ЗаперетьЗдание(открыть)
ЗаперетьЗдание(открывать)
// +++++++++++++++++
// она несла на плечах своего мужа.
// ^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:нести{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then 1
}
// +++++++++++++++++++++
// И была опасность, что когда-нибудь откажет дыхательный аппарат.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отказать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then -2
}
// ++++++++++++++++++++++
// Ты знаешь, что на следующий день должен был приехать мой муж.
// ^^^ ^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:должный{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
инфинитив:*{}
}
}
then -100
}
// Двое гонцов из Мурманска должны были прибыть ночным поездом.
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:должный{}.{
<OBJECT>*:*{ ПАДЕЖ:РОД }
инфинитив:*{}
}
}
then -100
}
// ++++++++++++++++++++++
// чувашскими законотворцами был взят проект Федерального закона
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { прилагательное:*{ КРАТКИЙ СТРАД ПРИЧАСТИЕ }.<OBJECT>*:*{ падеж:род } }
then -5
}
// ++++++++++++++++++++++
// ружье его было тут
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.'его'{ class:прилагательное } }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.'ее'{ class:прилагательное } }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.'их'{ class:прилагательное } }
then -5
}
// +++++++++++++++++++++++++++
// его отучают пить из-под крана
tree_scorer language=Russian
{
if context { инфинитив:*{}.
<LEFT_AUX_VERB>глагол:отучать{}.
ОдушОбъект{ ПАДЕж:ВИН } }
then 2
}
// +++++++++++++++++++++++++++++++
// Смелость города берёт
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:брать{}.<OBJECT>существительное:*{ падеж:вин } }
then 1
}
// --------------------------------
// это открытие его удивило
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:удивить{}.<OBJECT>ОдушОбъект{ падеж:вин } }
then 2
}
// ++++++++++++++++++++++++++++++++++++++++++++
// Ветерок был приятным
// ^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { глагол:быть{}.{
thema=<SUBJECT>*:*{}
rhema=<RHEMA>прилагательное:*{}
}
}
then adj_noun_score(rhema,thema)
}
// Выбор фруктов слаб
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { a=прилагательное:*{ КРАТКИЙ}.n=<SUBJECT>СУЩЕСТВИТЕЛЬНОЕ:*{}
}
then adj_noun_score(a,n)
}
// Воздух становился всё холоднее
// ^^^^^^ ^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { глагол:становиться{}.{
thema=<SUBJECT>*:*{}
rhema=прилагательное:*{}
}
}
then adj_noun_score(rhema,thema)
}
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { глагол:стать{}.{
thema=<SUBJECT>*:*{}
rhema=прилагательное:*{}
}
}
then adj_noun_score(rhema,thema)
}
// -----------------------------------
#define VerbInstr(v,w) \
#begin
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:v{}.<OBJECT>существительное:*{ падеж:твор } }
then w
}
#end
VerbInstr(ограничиться,2)
VerbInstr(интересоваться,2)
VerbInstr(заинтересоваться,2)
VerbInstr(поинтересоваться,2)
VerbInstr(пренебрегать,2)
VerbInstr(пренебречь,2)
VerbInstr(увенчаться,2)
// ----------------------------------
// Все звали ее Верочкой...
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:звать{}.{
<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН }
<OBJECT>существительное:*{ ПАДЕЖ:ТВОР }
}
}
then 2
}
// ----------------------------------
/*
wordentry_set ПредлогНаправления = предлог:{ на, в, под, через }
// дракону на спину сел
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ ~ПАДЕЖ:ДАТ }.{
<OBJECT>*:*{ ПАДЕЖ:ДАТ }
<PREPOS_ADJUNCT>ПредлогНаправления.*:*{ ПАДЕЖ:ВИН }
}
}
then 8
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{ ~ПАДЕЖ:ДАТ }.{
<OBJECT>*:*{ ПАДЕЖ:ДАТ }
<PREPOS_ADJUNCT>ПредлогНаправления.*:*{ ПАДЕЖ:ВИН }
}
}
then 8
}
*/
// -----------------------------------
// Официант денег не взял.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:взять{}.{
частица:не{}
<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД }
}
}
then 2
}
// ----------------------------------
// эти последние энергично пошли им навстречу.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пойти{}.послелог:навстречу{}.*:*{ падеж:дат } }
then 5
}
// Он сделал шаг ей навстречу.
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сделать{}.{ <OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН } послелог:навстречу{}.*:*{ падеж:дат } } }
then 5
}
// ---------------------------------
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:объявить{}.{
<OBJECT>*:*{ падеж:вин }
предлог:о{}
}
}
then -100
}
// ----------------------------------
// именно поэтому она собиралась предложить им очень простой выбор.
// ^^^^^^^^^^ ^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:предложить{}.{
<OBJECT>*:*{ падеж:дат }
<OBJECT>*:*{ падеж:вин }
}
}
then 5
}
// -----------------------------------------------
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:править{}.<OBJECT>существительное:*{ <в_класс>существительное:страна{} ПАДЕЖ:ТВОР } }
then 5
}
// ----------------------------------
// мы уже начали за вас волноваться.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:волноваться{}.предлог:за{}.*:*{ падеж:вин } }
then 5
}
// ----------------------------------
// ей следовало бы проверить зрение.
tree_scorer ВалентностьГлагола language=Russian
{
if context { безлич_глагол:следует{}.{ *:*{ падеж:дат } инфинитив:*{} } }
then 2
}
// ----------------------------------
// как легко превратить в кляксу живого человека
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:превратить{}.{ <OBJECT>*:*{ падеж:вин } предлог:в{}.*:*{ падеж:вин } } }
then 2
}
// ----------------------------------
// мне надо было встать
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.{
БезличСвязка0
безлич_глагол:*{ ~ТИП_ПРЕДИКАТИВ:БЫЛО_СВЯЗКА }
}
}
then -5
}
// ----------------------------------
// Уточняем согласование подлежащего и
// атрибута для связочных глаголов:
//
wordentry_set СвязочныеГлаголы=
{
rus_verbs:стать{},
rus_verbs:становиться{},
rus_verbs:быть{},
rus_verbs:бывать{},
rus_verbs:оказаться{},
rus_verbs:оказываться{},
rus_verbs:получиться{},
rus_verbs:получаться{}
}
// Он может стать главным
// ^^ ^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { СвязочныеГлаголы.{
sbj=<SUBJECT>*:*{ ЧИСЛО:ЕД }
прилагательное:*{ ПАДЕЖ:ТВОР ЧИСЛО:ЕД ~КРАТКИЙ !=sbj:РОД }
} }
then -2
}
// Ты можешь стать главным
// ^^ ^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { СвязочныеГлаголы.{
sbj=<SUBJECT>местоимение:я{ ЧИСЛО:ЕД ~лицо:3 }
прилагательное:*{ ПАДЕЖ:ТВОР ЧИСЛО:ЕД ~КРАТКИЙ РОД:СР }
} }
then -2
}
// ----------------------------------
#define НеГлагРодЕд(v,n,w) \
#begin
tree_scorer ВалентностьГлагола language=Russian
{
if context {
rus_verbs:v{}.{
частица:не{}
<OBJECT>существительное:n{ падеж:род число:ед }
}
} then w
}
#end
// Америка не имеет права вмешиваться во внутренние дела России
// ^^^^^^^^^^^^^^
НеГлагРодЕд(иметь,право,2)
// Ни один прокурор такого разрешения не даст.
НеГлагРодЕд(дать,разрешение,8)
// ----------------------------------
// Надежде приходилось, чтобы успеть вставить свои ответы между его репликами, произносить слова со скоростью пулеметной очереди.
tree_scorer ВалентностьГлагола language=Russian
{
if context { безлич_глагол:приходится{}.инфинитив:*{ вид:несоверш } }
then 2
}
// ----------------------------------
// Мы внедрили в его организацию соглядатая
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:внедрить{}.существительное:*{ падеж:вин } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:внедрять{}.существительное:*{ падеж:вин } }
then 1
}
// ----------------------------------
// Основание качнулось, зажатое манипуляторами.
// ^^^^^^^^^ ^^^^^^^
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { глагол:*{}.{
n3=<SUBJECT>*:*{}
<SEPARATE_ATTR>*:*{ ПАДЕЖ:ИМ =n3:РОД =n3:ЧИСЛО }
} }
then 2
}
// День выдался ненастный.
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { *:*{}.{ sbj=<SUBJECT>существительное:*{} attr=<SEPARATE_ATTR>прилагательное:*{ ПАДЕЖ:ИМ =sbj:РОД =sbj:ЧИСЛО } } }
then adj_noun_score(attr,sbj)
}
// Такое было удовольствие!
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { глагол:быть{}.{
n3=<SUBJECT>*:*{}
attr=<SEPARATE_ATTR>*:*{ ПАДЕЖ:ИМ =n3:РОД =n3:ЧИСЛО }
} }
then adj_noun_score(attr,n3)
}
// Ответы я давал самые несуразные.
// ^^^^^^ ^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { глагол:*{}.{
n3=<OBJECT>*:*{}
<SEPARATE_ATTR>*:*{ =n3:ПАДЕЖ =n3:РОД =n3:ЧИСЛО }
} }
then 2
}
// ------------------------------------------------------------------
// Некоторые модальные редко употребляются без инфинитива:
// Разве можно в такую погоду как следует настроиться на мысль о преступлении?
// ^^^^^
wordentry_set МодальныеТребуютИнф=
{
безлич_глагол:можно{},
безлич_глагол:хочется{},
безлич_глагол:захотелось{},
глагол:мочь{},
глагол:смочь{}
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.<LEFT_AUX_VERB>МодальныеТребуютИнф }
then 7
}
// -------------------------------------------
// а им уже приходилось умирать вместе
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.{ <SUBJECT>местоимение:*{ падеж:дат } безлич_глагол:*{ МОДАЛЬНЫЙ } } }
then 1
}
// Ей вдруг захотелось закричать от разочарования.
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.{ <OBJECT>"ей"{ падеж:твор } безлич_глагол:*{ МОДАЛЬНЫЙ } } }
then -2
}
// Ей было приятно думать об этом.
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.{ <OBJECT>"ей"{ падеж:твор } } }
then -1
}
// ------------------------------------------------------
// им давно пора уходить.
wordentry_set БезличнМодальн=безлич_глагол:{ пора, надо, нужно }
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { инфинитив:*{}.{ *:*{ падеж:дат } БезличнМодальн } }
then 1
}
// -------------------------------------------------------
// у нас мало времени!
tree_scorer ВалентностьПредиката language=Russian
{
if context { СчетнСвязка.{ предлог:у{} существительное:время{ падеж:род } } }
then 10
}
// ----------------------------------------------
// ЕСЛИ не сочетается с императивом:
// - Не объясняйте, если не хотите.
// ^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ наклонение:побуд }.'если' }
then -10
}
// --------------------------------------------
// Частица НЕТ не всегда выполняет роль предикатива, иногда
// она выступает в роли вводной частицы, аналогично ДА:
// - Нет, вы не понимаете.
// ^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { частица:нет{}.[not]<OBJECT>*:*{} }
then -2
}
// ---------------------------------------------
// Позади никого не было.
// ^^^^^^^^^^^^^^
// Пыли не было
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{ наклонение:изъяв число:ед род:ср время:прошедшее }.{ частица:не{} <OBJECT>*:*{ ПАДЕЖ:РОД } } }
then 4
}
// Радости не было предела
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{ наклонение:изъяв число:ед род:ср время:прошедшее }.
{
частица:не{}
<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ }
<OBJECT>'предела'{ ПАДЕЖ:РОД }
}
}
then 6
}
// ---------------------------------------------
wordentry_set ОтрицМестоим = местоим_сущ:{ никто, ничто }
// Местоимение НИЧТО и НИКТО в косвенных падежах обычно прикрепляются
// только к глаголу с частией НЕ:
//
// Стояла ничем не нарушаемая тишина.
// ~~~~~~ ^^^^^ ^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.{ [not]частица:не{} <OBJECT>ОтрицМестоим{} } }
then -5
}
// -------------------------------------------------------
// Я имею на это право.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:иметь{}.{ <OBJECT>существительное:право{ ПАДЕЖ:ВИН } <PREPOS_ADJUNCT>предлог:на{}.*:*{ ПАДЕЖ:ВИН } } }
then 1
}
// Они, должно быть, спустились с горы.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:спуститься{}.предлог:с{}.*:*{ падеж:вин } }
then -5
}
// ------------------------------------------------------------
// наконец усталость дала о себе знать.
// ^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:знать{}.rus_verbs:дать{} }
then 2
}
// ------------------------------------------------------------
// Но никто не обращал на них внимания.
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обращать{}.предлог:на{}.*:*{ ПАДЕЖ:ПРЕДЛ } }
then -1
}
// распространяться по территории штата
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:распространяться{}.предлог:по{}.*:*{ ПАДЕЖ:ВИН } }
then -1
}
// я собираюсь с тобой в прятки поиграть
// ^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поиграть{}.предлог:в{}.'прятки'{ ПАДЕЖ:ВИН } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:играть{}.предлог:в{}.'прятки'{ ПАДЕЖ:ВИН } }
then 1
}
// бежать, повалявшись в снегу, обратно в тепло
// ^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:бежать{}.предлог:в{}.*:*{ ПАДЕЖ:ВИН ОДУШ:НЕОДУШ } }
then 1
}
// Ты сама ко мне лезла!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:лезть{}.предлог:к{}.*:*{ ПАДЕЖ:ДАТ } }
then 1
}
// В действительности же дело обстояло не так.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:обстоять{}.<SUBJECT>существительное:дело{} }
then 1
}
// Тем дело пока и кончилось.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:кончиться{}.{ <SUBJECT>существительное:дело{} <OBJECT>*:*{ ПАДЕЖ:ТВОР } } }
then 1
}
// На этом дело и кончилось.
// ^^^^ ^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:кончиться{}.<SUBJECT>существительное:дело{} }
then 1
}
// В действительности же дело обстояло не так.
// ^^^^ ^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:обстоять{}.<SUBJECT>существительное:дело{} }
then 1
}
// Озеленение на этом не закончится.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:закончиться{}.предлог:на{}.*:*{ ПАДЕЖ:ПРЕДЛ } }
then 1
}
// Ты что-то от меня скрываешь?
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:скрывать{}.предлог:от{}.ОдушОбъект{ ПАДЕЖ:РОД } }
then 1
}
// мы будем атаковать
// ^^^^^^^^^^^^^^^
tree_scorer ГлагИнф language=Russian generic
{
if context { инфинитив:*{ ВИД:СОВЕРШ }.МодальныеТолькоНесоверш }
then -100
}
// Ужин был подан, и все сели за стол.
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сесть{}.предлог:за{}.существительное:стол{} }
then 1
}
// Ты совсем отстал от жизни.
// ^^^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отстать{}.предлог:от{} }
then 2
}
// Тут есть над чем задуматься
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:задуматься{}.предлог:над{} }
then 2
}
// Пора было положить этому конец.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:положить{}.{ <OBJECT>существительное:конец{ ПАДЕЖ:ВИН } <OBJECT>*:*{ ПАДЕЖ:ДАТ } } }
then 2
}
// Задержать преступников по горячим следам милиционерам не удалось.
// ^^^^^^^^^ ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:задержать{}."по"."горячим"."следам" }
then 4
}
// ----------------------------
// Особо обрабатываем ситуацию с появлением РОДИТЕЛЬНОЙ валентности в случае,
// когда модальный глагол стоит в отрицательной форме:
//
// Ломать вы ничего не хотите.
// ^^^^^^ ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ ПАДЕЖ:ВИН }
.{
<LEFT_AUX_VERB>глагол:*{}.<NEGATION_PARTICLE>частица:не{}
<OBJECT>*:*{ ПАДЕЖ:РОД }
}
}
then 3
}
// ----------------------------------------
// Они не хотят ее знать.
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:знать{}.{ <LEFT_AUX_VERB>глагол:хотеть{} } }
then 5
}
// Никому до тебя нет дела
tree_scorer ВалентностьПредиката language=Russian
{
if context { частица:нет{}.{ <OBJECT>'дела'{ падеж:род } <PREPOS_ADJUNCT>предлог:до{} } }
then 5
}
// Я не удостоил Ее ответом.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:удостоить{}.{ <OBJECT>*:*{ ПАДЕЖ:ДАТ } <OBJECT>'ответом' } }
then 2
}
// -----------------------------------------------
// Горю родителей нет предела.
tree_scorer ВалентностьПредиката language=Russian
{
if context { частица:нет{}.{ <OBJECT>'предела'{ падеж:род } *:*{ ПАДЕЖ:ДАТ } } }
then 5
}
// -----------------------------------------
// Он весь день провел со мной!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:провести{}.{ <OBJECT>'день'.'весь' <PREPOS_ADJUNCT>предлог:с{}.*:*{ падеж:твор } } }
then 4
}
// Рабочие день и ночь трудятся.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:трудиться{}.<ATTRIBUTE>'день'.'и'.'ночь' }
then 2
}
wordentry_set СчетныеНаречия=наречие:{ мало, немало, много, немного, маловато, многовато }
// Но и этого будет мало.
// ^^^^^^^^^^^^^^^^
// Контрпример:
// Несколько мгновений все было тихо.
// ~~~~~~~~~ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.{ <OBJECT>*:*{ падеж:род } <ATTRIBUTE>СчетныеНаречия } }
then 5
}
// Шуму было много, однако гора родила мышь.
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.{ <OBJECT>*:*{ падеж:парт } <ATTRIBUTE>СчетныеНаречия } }
then 5
}
// Я не удостоил Ее ответом.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:удостоить{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>'ответом' } }
then 2
}
word_set ЕеЕгоИхОбъект = { 'ее', 'его', 'их' }
// Аня неумело стиснула ее зубами.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ ПАДЕЖ:ВИН ~ПАДЕЖ:ТВОР }.
{
<OBJECT>ЕеЕгоИхОбъект{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
}
}
then 2
}
// Орлиц в поле зрения не оказалось.
// ^^^^^^^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { rus_verbs:оказаться{}.<PREPOS_ADJUNCT>предлог:в{}.'поле'{ РОД:СР ПАДЕЖ:ПРЕДЛ }.'зрения' }
then 2
}
// Я пересекла двор и села рядом с ней.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сесть{}.<PREPOS_ADJUNCT>предлог:с{}.<ATTRIBUTE>наречие:рядом{} }
then 2
}
// Я всегда стою, обучая кого-то.
// ^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:стоить{}.<SUBJECT>местоимение:я{ лицо:1 } }
then -2
}
// Окончив первый, принялся за второй.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приняться{}.<PREPOS_ADJUNCT>предлог:за{}.*:*{ ПАДЕЖ:ТВОР } }
then -2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приниматься{}.<PREPOS_ADJUNCT>предлог:за{}.*:*{ ПАДЕЖ:ТВОР } }
then -2
}
// Оставшихся в живых они же заперли в резервациях.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:остаться{}.<PREPOS_ADJUNCT>предлог:в{}.'живых' }
then 2
}
// Ворованные автомобили злоумышленники разбирали на запчасти и продавали.
// ^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:разбирать{}.<PREPOS_ADJUNCT>предлог:на{}.существительное:*{ падеж:вин одуш:неодуш } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:разобрать{}.<PREPOS_ADJUNCT>предлог:на{}.существительное:*{ падеж:вин одуш:неодуш } }
then 2
}
// Белолобый неприязненно смерил его взглядом.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смерить{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>'взглядом' } }
then 2
}
// Безмерно нибелунги о Зигфриде грустили.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:грустить{}.<PREPOS_ADJUNCT>предлог:о{}.<OBJECT>*:*{ падеж:предл } }
then 1
}
// Блондин потащил девчонку к двери;
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:потащить{}.<PREPOS_ADJUNCT>предлог:к{} }
then 1
}
// Сняв шляпу, Рэнналф прибавил шагу.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:прибавить{}.<OBJECT>'шагу'{ падеж:парт } }
then 3
}
// Хвалю я ее за это?
// ^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:хвалить{}.<PREPOS_ADJUNCT>предлог:за{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// Александр улыбнулся, пожирая её глазами.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пожирать{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } 'глазами' } }
then 2
}
// мне будет сорок один год
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:быть{ число:ед лицо:3 время:будущее }.
{
<SUBJECT>существительное:год{}.числительное:*{}
<OBJECT>*:*{ падеж:дат }
}
}
then 2
}
// Мне было двадцать три года.
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:быть{ число:ед род:ср время:прошедшее }.
{
<SUBJECT>существительное:год{}.числительное:*{}
<OBJECT>*:*{ падеж:дат }
}
}
then 2
}
// Устойчивый оборот: принять участие в чем-то:
//
// В экспедиции приняли участие много иностранцев.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:принять{}.{ <OBJECT>существительное:участие{ ПАДЕЖ:ВИН } <PREPOS_ADJUNCT>предлог:в{}.*:*{ падеж:предл } } }
then 1
}
// Женщина и ребенок с ног валились.
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:валиться{}.'с'.'ног' }
then 2
}
// Ведет оседлый и полуоседлый образ жизни.
// ^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:вести{}.<OBJECT>'образ'.'жизни' }
then 2
}
// Я обещался в точности исполнить поручение.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:исполнить{}.'в'.'точности'{ падеж:предл } }
then 2
}
// Впрочем, может быть и меньше.
// ~~~~~~
tree_scorer ВалентностьПредиката language=Russian
{
if context { СчетнСвязка.[not]<OBJECT>*:*{} }
then -3
}
// Проехали километра два.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:проехать{}.<OBJECT>существительное:километр{} }
then 4
}
// Прошли пять километров
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пройти{}.<OBJECT>существительное:километр{} }
then 4
}
// Пройдет много лет.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пройти{}.<SUBJECT>'лет'.'много' }
then 4
}
// Ничего не видит.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:видеть{}.<SUBJECT>'ничего' }
then -4
}
// Ничего не знает.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:знать{}.<SUBJECT>'ничего' }
then -4
}
// Ничего не боится.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:бояться{}.<SUBJECT>'ничего' }
then -4
}
// Взяли в клещи.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:взять{}.'в'.'клещи'{ ПАДЕЖ:ВИН} }
then 2
}
// К вам пришли!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:придти{}.'к'.*:*{ ПАДЕЖ:ДАТ } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:прийти{}.'к'.*:*{ ПАДЕЖ:ДАТ } }
then 1
}
// Сергиенко воспользовался моментом.
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:воспользоваться{}.[not]<OBJECT>*:*{ ПАДЕЖ:ТВОР } }
then -1
}
// Готовиться времени нет.
tree_scorer ВалентностьПредиката language=Russian
{
if context { частица:нет{}.'времени'.<INFINITIVE>инфинитив:*{} }
then 4
}
// Дал время подумать.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:дать{}.<OBJECT>существительное:время{ падеж:вин }.<INFINITIVE>инфинитив:*{} }
then 4
}
// -------------------------------------------------------------------------------
// Ночь выдается беспокойная.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:выдаваться{}.<SUBJECT>СущСоЗначВремКакОбст1{ ПАДЕЖ:ИМ } }
then 4
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:выдаться{}.<SUBJECT>СущСоЗначВремКакОбст1{ ПАДЕЖ:ИМ } }
then 4
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:выдаваться{}.<ATTRIBUTE>СущСоЗначВремКакОбст1{} }
then -10
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:выдаться{}.<ATTRIBUTE>СущСоЗначВремКакОбст1{} }
then -10
}
// -------------------------------------------------------------------------------
// Что говорит свинец?
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:говорить{}.<SUBJECT>местоим_сущ:что{} }
then -3
}
// В детях эта программа усиливается во много раз.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:усиливаться{}."во"."раз"."много" }
then 5
}
// Я посмотрел на часы.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:посмотреть{}."на".*{ ПАДЕЖ:ВИН } }
then 3
}
// К вам пришли!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:придти{}."к".ОдушОбъект }
then 3
}
// Он бросил взгляд на часы. (БРОСИТЬ ВЗГЛЯД НА что-то)
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:бросить{}.{ <OBJECT>"взгляд"{ ПАДЕЖ:ВИН } <PREPOS_ADJUNCT>"на".*:*{ ПАДЕЖ:ВИН } } }
then 3
}
// Женщина и ребенок с ног валились. (ВАЛИТЬСЯ С НОГ)
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:валиться{}."с"."ног" }
then 3
}
// стыдно ребятам в глаза смотреть. (СМОТРЕТЬ В ГЛАЗА)
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смотреть{}."в"."глаза"{ ПАДЕЖ:ВИН } }
then 3
}
// Надежнее иметь дело со взрослыми. (ИМЕТЬ ДЕЛО С кем-то/чем-то)
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:иметь{}.{ <OBJECT>существительное:дело{ падеж:вин } <PREPOS_ADJUNCT>предлог:с{}.*:*{ ПАДЕЖ:ТВОР } } }
then 3
}
// Вдохновлял он ее и на поэмы. (ВДОХНОВЛЯТЬ/ВДОХНОВИТЬ НА что-то)
// ^^^^^^^^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:вдохновлять{}.<PREPOS_ADJUNCT>предлог:на{}.*:*{ ПАДЕЖ:ВИН } }
then 3
}
// Оставшихся в живых они же заперли в резервациях. (ОСТАТЬСЯ В ЖИВЫХ)
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:остаться{}.<PREPOS_ADJUNCT>предлог:в{}.'живых' }
then 3
}
// Я стояла, провожая его взглядом. (ПРОВОЖАТЬ кого-то/что-то ВЗГЛЯДОМ)
// ^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:провожать{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } 'взглядом' } }
then 3
}
// Эпидемии гриппа не ожидается
tree_scorer ВалентностьГлагола language=Russian
{
if context { "ожидается".{ <OBJECT>*:*{ ПАДЕЖ:РОД } 'не' } }
then 3
}
// --------------------------------------------------------------------------
// Прикажи дать коньяку.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}.<OBJECT>*:*{ ПАДЕЖ:ПАРТ <в_класс>СУЩЕСТВИТЕЛЬНОЕ:НАПИТОК{} } }
then 6
}
// Там дела важнее.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { 'дела'.<ATTRIBUTE>НАРЕЧИЕ:*{ СТЕПЕНЬ:СРАВН } }
then -10
}
// --------------------------------------------------------------------
// Что делает Танасчишин?
// ~~~~~~~~~~
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:делать{}.<SUBJECT>местоим_сущ:что{} }
then -3
}
// -------------------------------------------------------
// Нельзя допустить атрофии.
tree_scorer ВалентностьПредиката language=Russian
{
if context { инфинитив:допустить{}.{ <LEFT_AUX_VERB>безлич_глагол:Нельзя{} <OBJECT>*:*{ падеж:род } } }
then 3
}
// --------------------------------------------------------
// Надо Дорошенко сказать.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сказать{}.<OBJECT>существительное:*{ ОДУШ:ОДУШ ПАДЕЖ:ТВОР } }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сказать{}.<OBJECT>существительное:*{ ОДУШ:ОДУШ ПАДЕЖ:ВИН } }
then -5
}
// --------------------------------------------------------------
// Тем не менее досталось всем.
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:достаться{}.<ATTRIBUTE>'всем'{ ПАДЕЖ:ТВОР } }
then -20
}
// Наконец достигли вершины.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:достичь{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД } }
then 3
}
// --------------------------------------------------------------
// Возглавляет его мэр.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:возглавлять{}.[not]<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then -3
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:возглавлять{}.<OBJECT>существительное:*{ ПАДЕЖ:ВИН } }
then -3
}
/*
// Засыпаю его вопросами.
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:засыпать{ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ }.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>'вопросами' } }
then 2
}
*/
// Разбудила его Надя.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:разбудить{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <SUBJECT>*:*{} } }
then 2
}
// Прошло две недели.
tree_scorer ВалентностьПредиката language=Russian
{
if context { 'прошло'.<SUBJECT>СущСоЗначВрем{ ПАДЕЖ:РОД }.числительное:*{} }
then 2
}
// Я просидел дома весь день
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:просидеть{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } }
then 2
}
// Сегодня я весь день читал.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:читать{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } }
then 2
}
// я буду работать весь день
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:работать{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } }
then 2
}
// вместе они шли весь день.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:идти{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } }
then 2
}
// бой продолжался весь день.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:продолжаться{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } }
then 2
}
// битва длилась весь день.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:длиться{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } }
then 2
}
// мы играли во дворе целый день
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:играть{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'целый'{ ПАДЕЖ:ВИН } }
then 2
}
// У меня к тебе дело
// ~~~~~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:деть{ род:ср }.предлог:к{}.*:*{ падеж:дат } }
then -10
}
// дайте им три часа.
// ^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:дать{}.<OBJECT>существительное:час{}.числительное:*{} }
then 5
}
// Важное значение имеет и нестационарность Метагалактики.
// ^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:иметь{}.<OBJECT>существительное:значение{}.'важное' }
then 10
}
// Я не теряю надежды.
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:терять{}.{ <NEGATION_PARTICLE>частица:не{} <OBJECT>существительное:надежда{ падеж:род число:ед } } }
then 1
}
// Вы не знаете Дезире?
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.<OBJECT>существительное:*{ одуш:одуш падеж:твор } }
then -5
}
// Я целую Викторию...
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:целовать{}.<OBJECT>существительное:*{ одуш:одуш падеж:дат } }
then -5
}
// Благоустройство кладбища продолжалось и летом.
// ^^^^^^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:продолжаться{}.<ATTRIBUTE>существительное:лето{ падеж:твор } }
then 5
}
// ----------------------------------------------------------------
// Ей нужен был отдых.
tree_scorer ВалентностьПредиката language=Russian
{
if context { прилагательное:нужный{ краткий }.'ей'{ падеж:твор } }
then -5
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { прилагательное:нужный{ краткий }.'им'{ падеж:твор } }
then -5
}
// - Я тебе дам знать .
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:знать{}.rus_verbs:дать{} }
then 5
}
// Для отправителя они не представляли опасности.
// ^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:представлять{}.'опасности'{ ПАДЕЖ:РОД } }
then 5
}
// К вам это не имело отношения.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:иметь{}.'отношения'{ ЧИСЛО:МН } }
then -1
}
// ты встала на его пути
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:встать{}.'на'.'пути'{ ПАДЕЖ:ВИН } }
then -2
}
// Она хотела стать моей
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:хотеть{}.<OBJECT>существительное:стать{} }
then -10
}
// откуда нам это знать?
tree_scorer ВалентностьПредиката language=Russian
{
if context { инфинитив:знать{}.{ <ATTRIBUTE>наречие:откуда{} <OBJECT>*:*{ падеж:дат } } }
then 2
}
// друид встал на их пути
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:встать{}.<PREPOS_ADJUNCT>предлог:на{}.<OBJECT>существительное:путь{ падеж:вин } }
then -2
}
// «Мы вытолкнули Украину из Русского мира»
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:вытолкнуть{}.<PREPOS_ADJUNCT>предлог:из{} }
then 2
}
// Владимир Путин объявил финансовые пирамиды вне закона
// ^^^^^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:объявить{}.<PREPOS_ADJUNCT>предлог:вне{} }
then 2
}
// Содержание их было однообразно.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rhema=прилагательное:*{ КРАТКИЙ ЧИСЛО:ЕД РОД:СР }.{ thema=<SUBJECT>существительное:*{ ЧИСЛО:ЕД РОД:СР } } }
then adj_noun_score(rhema,thema)
}
// Отдам краснохвостого сома в хорошие руки
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отдать{}.предлог:в{}.'руки'.'хорошие' }
then 5
}
// ----------------------------------------------------------------
// Приобретает массовый характер Стахановское движение.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приобретать{}.<OBJECT>существительное:характер{}.<ATTRIBUTE>прилагательное:массовый{} }
then 5
}
// Фашистские стрелки открывают ответный огонь.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:открывать{}.{ <SUBJECT>существительное:стрелок{} <OBJECT>существительное:огонь{} } }
then 5
}
// Документы эти разрабатывались соответствующими начальниками.
// Старый хрыч обернулся добродушным дедулей.
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.<ATTRIBUTE>существительное:*{ падеж:твор одуш:одуш } }
then -2
}
// Он смотрел на танцующих вытаращенными глазами.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смотреть{}.предлог:на{}.прилагательное:*{ падеж:предл } }
then -5
}
// Ей в глаза смотрела дама червей.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смотреть{}.{ предлог:в{} "ей"{падеж:твор} } }
then -5
}
// Ей даже передалось его нервное напряжение.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:передаться{}."ей"{падеж:твор} }
then -5
}
// Ей ничего не приходило на ум.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приходить{}."ей"{падеж:твор} }
then -5
}
// Ей и так все было ясно.
tree_scorer ВалентностьГлагола language=Russian
{
if context { "было"."ей"{падеж:твор} }
then -5
}
// Ей отвели пять часов на раздумья.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отвести{}."ей"{падеж:твор} }
then -5
}
// Ей смертельно надоели эти смертельные игры.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:надоесть{}."ей"{падеж:твор} }
then -5
}
// Ей пришлось нелегко в прошлом году.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:прийтись{}."ей"{падеж:твор} }
then -5
}
// Ей отвечали только изумленные печальные взгляды.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отвечать{}."ей"{падеж:твор} }
then -5
}
// Ей просто дали пипка под зад.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}."ей"{падеж:твор} }
then -5
}
// Ей все виделось в черном цвете.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:видеться{}."ей"{падеж:твор} }
then -5
}
// Ей в голову пришла одна мысль.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:прийти{}."ей"{падеж:твор} }
then -5
}
// Ей становилось трудно даже держаться прямо;
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:становиться{}."ей"{падеж:твор} }
then -5
}
// Ей бы и не дали вернуться.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}."ей"{падеж:твор} }
then -5
}
// Ей всегда доставляло удовольствие плести интриги.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:доставлять{}."ей"{падеж:твор} }
then -5
}
// Ей доставило немало удовольствия унизить меня.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:доставить{}."ей"{падеж:твор} }
then -5
}
// Ей отдается вся энергия творящего артиста.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отдаваться{}."ей"{падеж:твор} }
then -5
}
// Ей заранее был известен результат взрыва.
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:*{краткий}."ей"{падеж:твор} }
then -2
}
// Ей ставят капельницы и делают уколы.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ставить{}."ей"{падеж:твор} }
then -5
}
// Ей вызвали «скорую помощь».
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:вызвать{}."ей"{падеж:твор} }
then -5
}
// Ей подражали все девушки Советского Союза.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подражать{}."ей"{падеж:твор} }
then -5
}
// Ей разрешили оформить опеку над Сашей!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:разрешить{}."ей"{падеж:твор} }
then -5
}
// Ей Самсонова подавай, шофера автобазы!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подавать{}."ей"{падеж:твор} }
then -5
}
// Ему это с рук не сойдет.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сойти{}."с"."рук" }
then 5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { "это"."с"."рук" }
then -10
}
// Ему хотелось душу из нее вытрясти.
// ~~~~~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { существительное:душа{}."из".местоимение:*{} }
then -10
}
// Ему просто не приходилось этого делать.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:делать{}."этого"{падеж:вин} }
then -10
}
// Ему хотелось драки, хотелось убить.
tree_scorer ВалентностьГлагола language=Russian
{
if context { "хотелось".<OBJECT>существительное:*{число:мн падеж:вин} }
then -5
}
// А что со мной могло случиться?
// ~~~~~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { "что".предлог:с{} }
then -10
}
// А раньше-то что молчал?
// ~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { "молчал".<OBJECT>"что" }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { "молчал".<SUBJECT>"что" }
then -100
}
// А ты с ними по-русски говори.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:говорить{}.ПРЕДЛОГ:С{}.МЕСТОИМЕНИЕ:*{ПАДЕЖ:ТВОР} }
then 1
}
// ----------------------------------------------------------------
#define vap(v,adv,p,w) \
#begin
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:v{}.<PREPOS_ADJUNCT>ПРЕДЛОГ:p{}.<ATTRIBUTE>НАРЕЧИЕ:adv{} }
then w
}
#end
vap(стоять,впритык,к,1) // Шкаф стоит впритык к столу.
vap(стоять,вплотную,к,1) // Шкаф стоит вплотную к столу.
vap(бежать,следом,за,2) // она как раз начала бежать следом за ним
vap(быть,рядом,с,2) // он был рядом с дверью
vap(пойти,следом,за,2) // Катя пошла следом за ними.
// Я приехал в Москву одновременно с братом.
// ^^^^^^^ ^^^^^^^^^^^^^^
vap(приехать,одновременно,с,1)
vap(прийти,одновременно,с,1)
vap(прибыть,одновременно,с,1)
vap(появиться,одновременно,с,1)
// Петя положил яблоки вместе с картошкой.
// ^^^^^^^ ^^^^^^^^
vap(положить,вместе,с,1)
vap(ложить,вместе,с,1)
vap(положить,слева,от,2) // Положи книгу слева от тетради
vap(глядеть,прямо,в,5) // глядя прямо в ее круглые карие глаза, произнес
vap(посмотреть,прямо,в,5)
vap(смотреть,прямо,в,5)
vap(заглянуть,прямо,в,5)
vap(швырнуть,прямо,в,5) // Он подлетает к башне и... сейчас кибер швырнет нашего гладиатора прямо в ее пустую утробу.
vap(швырять,прямо,в,5)
vap(кинуть,прямо,в,5)
vap(кидать,прямо,в,5)
| Когда он вошел, все стаканы попадали с полки. ^^^^^^^^^^ | tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:падать{}.предлог:с{}.*:*{ падеж:род } } then 2 }
| 12,629,462 | [
1,
145,
253,
145,
127,
145,
116,
145,
117,
145,
113,
225,
145,
127,
145,
126,
225,
145,
115,
145,
127,
146,
235,
145,
118,
145,
124,
16,
225,
145,
115,
146,
228,
145,
118,
225,
146,
228,
146,
229,
145,
113,
145,
123,
145,
113,
145,
126,
146,
238,
225,
145,
128,
145,
127,
145,
128,
145,
113,
145,
117,
145,
113,
145,
124,
145,
121,
225,
146,
228,
225,
145,
128,
145,
127,
145,
124,
145,
123,
145,
121,
18,
11794,
3602,
20254,
20254,
66,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3413,
67,
1017,
8922,
225,
145,
245,
145,
113,
145,
124,
145,
118,
145,
126,
146,
229,
145,
126,
145,
127,
146,
228,
146,
229,
146,
239,
145,
246,
145,
124,
145,
113,
145,
116,
145,
127,
145,
124,
145,
113,
2653,
33,
54,
5567,
2779,
288,
309,
819,
288,
436,
407,
67,
502,
2038,
30,
145,
128,
145,
113,
145,
117,
145,
113,
146,
229,
146,
239,
24647,
145,
128,
146,
227,
145,
118,
145,
117,
145,
124,
145,
127,
145,
116,
30,
146,
228,
2916,
4509,
30,
14,
95,
225,
145,
128,
145,
113,
145,
117,
145,
118,
145,
119,
30,
146,
227,
145,
127,
145,
117,
289,
289,
1508,
576,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/Math.sol";
import "@pancakeswap/pancake-swap-lib/contracts/math/SafeMath.sol";
import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../../library/legacy/RewardsDistributionRecipient.sol";
import "../../library/legacy/Pausable.sol";
import "../../interfaces/legacy/IStrategyHelper.sol";
import "../../interfaces/IPancakeRouter02.sol";
import "../../interfaces/legacy/IStrategyLegacy.sol";
interface IPresale {
function totalBalance() view external returns(uint);
function flipToken() view external returns(address);
}
contract BunnyPool is IStrategyLegacy, RewardsDistributionRecipient, ReentrancyGuard, Pausable {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
/* ========== STATE VARIABLES ========== */
IBEP20 public rewardsToken; // bunny/bnb flip
IBEP20 public constant stakingToken = IBEP20(0xC9849E6fdB743d08fAeE3E34dd2D1bc69EA11a51); // bunny
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public rewardsDuration = 90 days;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
mapping(address => bool) private _stakePermission;
/* ========== PRESALE ============== */
address private constant presaleContract = 0x641414e2a04c8f8EbBf49eD47cc87dccbA42BF07;
address private constant deadAddress = 0x000000000000000000000000000000000000dEaD;
mapping(address => uint256) private _presaleBalance;
uint private constant timestamp2HoursAfterPresaleEnds = 1605585600 + (2 hours);
uint private constant timestamp90DaysAfterPresaleEnds = 1605585600 + (90 days);
/* ========== BUNNY HELPER ========= */
IStrategyHelper public helper = IStrategyHelper(0xA84c09C1a2cF4918CaEf625682B429398b97A1a0);
IPancakeRouter02 private constant ROUTER = IPancakeRouter02(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F);
/* ========== CONSTRUCTOR ========== */
constructor() public {
rewardsDistribution = msg.sender;
_stakePermission[msg.sender] = true;
_stakePermission[presaleContract] = true;
stakingToken.safeApprove(address(ROUTER), uint(~0));
}
/* ========== VIEWS ========== */
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balance() override external view returns (uint) {
return _totalSupply;
}
function balanceOf(address account) override external view returns (uint256) {
return _balances[account];
}
function presaleBalanceOf(address account) external view returns(uint256) {
return _presaleBalance[account];
}
function principalOf(address account) override external view returns (uint256) {
return _balances[account];
}
function withdrawableBalanceOf(address account) override public view returns (uint) {
if (block.timestamp > timestamp90DaysAfterPresaleEnds) {
// unlock all presale bunny after 90 days of presale
return _balances[account];
} else if (block.timestamp < timestamp2HoursAfterPresaleEnds) {
return _balances[account].sub(_presaleBalance[account]);
} else {
uint soldInPresale = IPresale(presaleContract).totalBalance().div(2).mul(3); // mint 150% of presale for making flip token
uint bunnySupply = stakingToken.totalSupply().sub(stakingToken.balanceOf(deadAddress));
if (soldInPresale >= bunnySupply) {
return _balances[account].sub(_presaleBalance[account]);
}
uint bunnyNewMint = bunnySupply.sub(soldInPresale);
if (bunnyNewMint >= soldInPresale) {
return _balances[account];
}
uint lockedRatio = (soldInPresale.sub(bunnyNewMint)).mul(1e18).div(soldInPresale);
uint lockedBalance = _presaleBalance[account].mul(lockedRatio).div(1e18);
return _balances[account].sub(lockedBalance);
}
}
function profitOf(address account) override public view returns (uint _usd, uint _bunny, uint _bnb) {
_usd = 0;
_bunny = 0;
_bnb = helper.tvlInBNB(address(rewardsToken), earned(account));
}
function tvl() override public view returns (uint) {
uint price = helper.tokenPriceInBNB(address(stakingToken));
return _totalSupply.mul(price).div(1e18);
}
function apy() override public view returns(uint _usd, uint _bunny, uint _bnb) {
uint tokenDecimals = 1e18;
uint __totalSupply = _totalSupply;
if (__totalSupply == 0) {
__totalSupply = tokenDecimals;
}
uint rewardPerTokenPerSecond = rewardRate.mul(tokenDecimals).div(__totalSupply);
uint bunnyPrice = helper.tokenPriceInBNB(address(stakingToken));
uint flipPrice = helper.tvlInBNB(address(rewardsToken), 1e18);
_usd = 0;
_bunny = 0;
_bnb = rewardPerTokenPerSecond.mul(365 days).mul(flipPrice).div(bunnyPrice);
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply)
);
}
function earned(address account) public view returns (uint256) {
return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]);
}
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(rewardsDuration);
}
/* ========== MUTATIVE FUNCTIONS ========== */
function _deposit(uint256 amount, address _to) private nonReentrant notPaused updateReward(_to) {
require(amount > 0, "amount");
_totalSupply = _totalSupply.add(amount);
_balances[_to] = _balances[_to].add(amount);
stakingToken.safeTransferFrom(msg.sender, address(this), amount);
emit Staked(_to, amount);
}
function deposit(uint256 amount) override public {
_deposit(amount, msg.sender);
}
function depositAll() override external {
deposit(stakingToken.balanceOf(msg.sender));
}
function withdraw(uint256 amount) override public nonReentrant updateReward(msg.sender) {
require(amount > 0, "amount");
require(amount <= withdrawableBalanceOf(msg.sender), "locked");
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
stakingToken.safeTransfer(msg.sender, amount);
emit Withdrawn(msg.sender, amount);
}
function withdrawAll() override external {
uint _withdraw = withdrawableBalanceOf(msg.sender);
if (_withdraw > 0) {
withdraw(_withdraw);
}
getReward();
}
function getReward() override public nonReentrant updateReward(msg.sender) {
uint256 reward = rewards[msg.sender];
if (reward > 0) {
rewards[msg.sender] = 0;
reward = _flipToWBNB(reward);
IBEP20(ROUTER.WETH()).safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function _flipToWBNB(uint amount) private returns(uint reward) {
address wbnb = ROUTER.WETH();
(uint rewardBunny,) = ROUTER.removeLiquidity(
address(stakingToken), wbnb,
amount, 0, 0, address(this), block.timestamp);
address[] memory path = new address[](2);
path[0] = address(stakingToken);
path[1] = wbnb;
ROUTER.swapExactTokensForTokens(rewardBunny, 0, path, address(this), block.timestamp);
reward = IBEP20(wbnb).balanceOf(address(this));
}
function harvest() override external {}
function info(address account) override external view returns(UserInfo memory) {
UserInfo memory userInfo;
userInfo.balance = _balances[account];
userInfo.principal = _balances[account];
userInfo.available = withdrawableBalanceOf(account);
Profit memory profit;
(uint usd, uint bunny, uint bnb) = profitOf(account);
profit.usd = usd;
profit.bunny = bunny;
profit.bnb = bnb;
userInfo.profit = profit;
userInfo.poolTVL = tvl();
APY memory poolAPY;
(usd, bunny, bnb) = apy();
poolAPY.usd = usd;
poolAPY.bunny = bunny;
poolAPY.bnb = bnb;
userInfo.poolAPY = poolAPY;
return userInfo;
}
/* ========== RESTRICTED FUNCTIONS ========== */
function setRewardsToken(address _rewardsToken) external onlyOwner {
require(address(rewardsToken) == address(0), "set rewards token already");
rewardsToken = IBEP20(_rewardsToken);
IBEP20(_rewardsToken).safeApprove(address(ROUTER), uint(~0));
}
function setHelper(IStrategyHelper _helper) external onlyOwner {
require(address(_helper) != address(0), "zero address");
helper = _helper;
}
function setStakePermission(address _address, bool permission) external onlyOwner {
_stakePermission[_address] = permission;
}
function stakeTo(uint256 amount, address _to) external canStakeTo {
_deposit(amount, _to);
if (msg.sender == presaleContract) {
_presaleBalance[_to] = _presaleBalance[_to].add(amount);
}
}
function notifyRewardAmount(uint256 reward) override external onlyRewardsDistribution updateReward(address(0)) {
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(rewardsDuration);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(rewardsDuration);
}
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint _balance = rewardsToken.balanceOf(address(this));
require(rewardRate <= _balance.div(rewardsDuration), "reward");
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardsDuration);
emit RewardAdded(reward);
}
function recoverBEP20(address tokenAddress, uint256 tokenAmount) external onlyOwner {
require(tokenAddress != address(stakingToken) && tokenAddress != address(rewardsToken), "tokenAddress");
IBEP20(tokenAddress).safeTransfer(owner(), tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner {
require(periodFinish == 0 || block.timestamp > periodFinish, "period");
rewardsDuration = _rewardsDuration;
emit RewardsDurationUpdated(rewardsDuration);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
modifier canStakeTo() {
require(_stakePermission[msg.sender], 'auth');
_;
}
/* ========== 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);
event RewardsDurationUpdated(uint256 newDuration);
event Recovered(address token, uint256 amount);
}
| ========== RESTRICTED FUNCTIONS ========== */ | function setRewardsToken(address _rewardsToken) external onlyOwner {
require(address(rewardsToken) == address(0), "set rewards token already");
rewardsToken = IBEP20(_rewardsToken);
IBEP20(_rewardsToken).safeApprove(address(ROUTER), uint(~0));
}
| 5,512,480 | [
1,
1432,
631,
8392,
2259,
15494,
13690,
55,
422,
1432,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
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,
444,
17631,
14727,
1345,
12,
2867,
389,
266,
6397,
1345,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
2867,
12,
266,
6397,
1345,
13,
422,
1758,
12,
20,
3631,
315,
542,
283,
6397,
1147,
1818,
8863,
203,
203,
3639,
283,
6397,
1345,
273,
467,
5948,
52,
3462,
24899,
266,
6397,
1345,
1769,
203,
3639,
467,
5948,
52,
3462,
24899,
266,
6397,
1345,
2934,
4626,
12053,
537,
12,
2867,
12,
1457,
1693,
654,
3631,
2254,
12,
98,
20,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
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;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
address public newOwner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferInitiated(
address indexed previousOwner,
address indexed newOwner
);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Throws if called by any account other than the specific function owner.
*/
modifier ownedBy(address _a) {
require( msg.sender == _a );
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to. Needs to be accepted by
* the new owner.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnershipAtomic(address _newOwner) public onlyOwner {
owner = _newOwner;
newOwner = address(0);
emit OwnershipTransferred(owner, _newOwner);
}
/**
* @dev Completes the ownership transfer by having the new address confirm the transfer.
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, msg.sender);
owner = msg.sender;
newOwner = address(0);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
newOwner = _newOwner;
emit OwnershipTransferInitiated(owner, _newOwner);
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
require( (allowed[msg.sender][_spender] == 0) || (_value == 0) );
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
// Overflow check: 2700 *1e6 * 1e18 < 10^30 < 2^105 < 2^256
uint constant public SUPPLY_HARD_CAP = 2700 * 1e6 * 1e18;
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
public
hasMintPermission
canMint
returns (bool)
{
require( totalSupply_.add(_amount) <= SUPPLY_HARD_CAP );
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract OPUCoin is MintableToken {
string constant public symbol = "OPU";
string constant public name = "Opu Coin";
uint8 constant public decimals = 18;
// -------------------------------------------
// Public functions
// -------------------------------------------
constructor() public { }
} | ------------------------------------------- Public functions ------------------------------------------- | contract OPUCoin is MintableToken {
string constant public symbol = "OPU";
string constant public name = "Opu Coin";
uint8 constant public decimals = 18;
constructor() public { }
} | 10,447,708 | [
1,
2443,
13849,
7224,
4186,
19134,
15392,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
7247,
17479,
885,
353,
490,
474,
429,
1345,
288,
203,
565,
533,
5381,
1071,
3273,
273,
315,
3665,
57,
14432,
203,
565,
533,
5381,
1071,
508,
273,
315,
3817,
89,
28932,
14432,
203,
565,
2254,
28,
5381,
1071,
15105,
273,
6549,
31,
203,
203,
565,
3885,
1435,
1071,
288,
289,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.0;
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
_setOwner(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
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");
}
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);
}
}
}
}
interface IERC721Receiver {
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
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);
}
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
interface IERC721 is IERC165 {
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;
}
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);
}
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);
}
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(), ".json")) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
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();
}
}
contract NFTgurus is ERC721Enumerable, Ownable {
using Strings for uint256;
string _baseTokenURI;
uint256 public _maxperTX = 77;
uint256 public _limit = 1100;
uint256 public _reserved = 323;
uint256 public _price = 0.09 ether;
address public fundWallet;
bool public _paused = true;
constructor(string memory baseURI, address _fundWallet) ERC721("NFT Gurus", "GURU") {
require(_fundWallet != address(0), "Zero address error");
setBaseURI(baseURI);
fundWallet = _fundWallet;
}
function MINT(uint256 num) public payable {
uint256 supply = totalSupply();
require( !_paused, "Sale paused" );
require( num <= _maxperTX, "You are exceeding limit of per transaction GURUS" );
require( supply + num <= _limit - _reserved, "Exceeds maximum GURUS supply" );
require( msg.value >= _price * num, "Ether sent is not correct" );
for(uint256 i; i < num; i++){
_safeMint( msg.sender, supply + i );
}
}
function giveAway(address _to, uint256 _amount) external onlyOwner() {
require( _to != address(0), "Zero address error");
require( _amount <= _reserved, "Exceeds reserved GURUS supply");
uint256 supply = totalSupply();
for(uint256 i; i < _amount; i++){
_safeMint( _to, supply + i );
}
_reserved -= _amount;
}
function walletOfOwner(address _owner) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for(uint256 i; i < tokenCount; i++){
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
// Just in case Eth does some crazy stuff
function setPrice(uint256 _newPrice) public onlyOwner() {
_price = _newPrice;
}
function setFundWallet(address _fundWallet) public onlyOwner() {
require(_fundWallet != address(0), "Zero address error");
fundWallet = _fundWallet;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setLimit(uint256 limit) public onlyOwner {
_limit = limit;
}
function setMaxPerWallet(uint256 limit) public onlyOwner {
_maxperTX = limit;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
function pause() public onlyOwner {
_paused = !_paused;
}
function withdrawAll() public payable onlyOwner {
require(payable(fundWallet).send(address(this).balance));
}
} | Token name Token symbol Mapping from token ID to owner address Mapping owner address to token count Mapping from token ID to approved address Mapping from owner to operator approvals | contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
string private _name;
string private _symbol;
mapping(uint256 => address) private _owners;
mapping(address => uint256) private _balances;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
}
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : "";
}
function _baseURI() internal view virtual returns (string memory) {
return "";
}
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
emit Transfer(address(0), to, tokenId);
}
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
} catch (bytes memory reason) {
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
} else {
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
} else {
) internal virtual {}
}
| 126,486 | [
1,
1345,
508,
3155,
3273,
9408,
628,
1147,
1599,
358,
3410,
1758,
9408,
3410,
1758,
358,
1147,
1056,
9408,
628,
1147,
1599,
358,
20412,
1758,
9408,
628,
3410,
358,
3726,
6617,
4524,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
4232,
39,
27,
5340,
353,
1772,
16,
4232,
39,
28275,
16,
467,
654,
39,
27,
5340,
16,
467,
654,
39,
27,
5340,
2277,
288,
203,
565,
1450,
5267,
364,
1758,
31,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
203,
565,
533,
3238,
389,
7175,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
3238,
389,
995,
414,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
3238,
389,
2316,
12053,
4524,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
1426,
3719,
3238,
389,
9497,
12053,
4524,
31,
203,
203,
97,
203,
565,
3885,
12,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
565,
289,
203,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
1071,
1476,
5024,
3849,
12,
654,
39,
28275,
16,
467,
654,
39,
28275,
13,
1135,
261,
6430,
13,
288,
203,
3639,
327,
203,
5411,
1560,
548,
422,
618,
12,
45,
654,
39,
27,
5340,
2934,
5831,
548,
747,
203,
5411,
1560,
548,
422,
618,
12,
45,
654,
39,
27,
5340,
2277,
2934,
5831,
548,
747,
203,
5411,
2240,
18,
28064,
1358,
12,
5831,
548,
1769,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
3410,
13,
1071,
1476,
5024,
3849,
1135,
261,
2
]
|
pragma solidity 0.4.25;
/**
*
* ╔╗╔╗╔╗╔══╗╔╗──╔╗──╔══╗╔═══╗──╔╗──╔╗╔═══╗
* ║║║║║║║╔╗║║║──║║──╚╗╔╝║╔══╝──║║──║║║╔══╝
* ║║║║║║║╚╝║║║──║║───║║─║╚══╗──║╚╗╔╝║║╚══╗
* ║║║║║║║╔╗║║║──║║───║║─║╔══╝──║╔╗╔╗║║╔══╝
* ║╚╝╚╝║║║║║║╚═╗║╚═╗╔╝╚╗║╚══╗╔╗║║╚╝║║║╚══╗
* ╚═╝╚═╝╚╝╚╝╚══╝╚══╝╚══╝╚═══╝╚╝╚╝──╚╝╚═══╝
* ┌──────────────────────────────────────┐
* │ Website: http://wallie.me │
* │ │
* │ CN Telegram: https://t.me/WallieCH │
* │ RU Telegram: https://t.me/wallieRU |
* │ * Telegram: https://t.me/WallieNews|
* |Twitter: https://twitter.com/Wallie_me|
* └──────────────────────────────────────┘
* | Youtube – https://www.youtube.com/channel/UC1q3sPOlXsaJGrT8k-BZuyw |
*
* * WALLIE - distribution contract *
*
* - Growth before 2000 ETH 1.1% and after 2000 ETH 1.2% in 24 hours
*
* Distribution: *
* - 10% Advertising, promotion
* - 5% for developers and technical support
*
* - Referral program:
* 5% Level 1
* 3% Level 2
* 1% Level 3
*
* - 3% Cashback
*
*
*
* Usage rules *
* Holding:
* 1. Send any amount of ether but not less than 0.01 ETH to make a contribution.
* 2. Send 0 ETH at any time to get profit from the Deposit.
*
* - You can make a profit at any time. Consider your transaction costs (GAS).
*
* Affiliate program *
* - You have access to a multy-level referral system for additional profit (5%, 3%, 1% of the referral's contribution).
* - Affiliate fees will come from each referral's Deposit as long as it doesn't change your wallet address Ethereum on the other.
*
*
*
*
* RECOMMENDED GAS LIMIT: 300000
* RECOMMENDED GAS PRICE: https://ethgasstation.info/
*
* The contract has been tested for vulnerabilities!
*
*/
contract Wallie
{
//Investor
mapping (address => Investor) public investors;
//Event the new investor
event NewInvestor(address _addr, uint256 _amount);
//Event of the accrual of cashback bonus
event CashbackBonus(address _addr, uint256 _amount, uint256 _revenue);
//Referral bonus accrual event
event RefererBonus(address _from, address _to, uint256 _amount, uint256 _revenue, uint256 _level);
//New contribution event
event NewInvestment(address _addr, uint256 _amount);
//The event of the new withdrawal
event NewWithdraw(address _addr, uint256 _amount);
//The event of changes in the balance of the smart contract
event ChangeBalance(uint256 _balance);
struct Investor {
//Member address
address addr;
//The address of the inviter
address referer;
//Deposit amount
uint256 investment;
//The time of the last contribution
uint256 investment_time;
//The time of the first contribution to the daily limit
uint256 investment_first_time_in_day;
//Deposit amount per day
uint256 investments_daily;
//Deposit income
uint256 investment_profit;
//Referral income
uint256 referals_profit;
//Cashback income
uint256 cashback_profit;
//Available balance income contributions
uint256 investment_profit_balance;
//Available referral income balance
uint256 referals_profit_balance;
//Available cashback income balance
uint256 cashback_profit_balance;
}
//Percentage of daily charges before reaching the balance of 2000 ETH
uint256 private constant dividends_perc_before_2000eth = 11; // 1.1%
//Percentage of daily charges after reaching the balance of 2000 ETH
uint256 private constant dividends_perc_after_2000eth = 12; // 1.2%
//The percentage of the referral bonus of the first line
uint256 public constant ref_bonus_level_1 = 5; // 5%
//Second line referral bonus percentage
uint256 public constant ref_bonus_level_2 = 3; // 3%
//The percentage of referral bonus is the third line
uint256 public constant ref_bonus_level_3 = 1; // 1%
//Cashback bonus percentage
uint256 public constant cashback_bonus = 3; // 3%
//Minimum payment
uint256 public constant min_invesment = 10 finney; // 0.01 eth
//Deduction for advertising
uint256 public constant advertising_fees = 15; // 15%
//Limit to receive funds on the same day
uint256 public constant contract_daily_limit = 100 ether;
//Lock entry tools
bool public block_investments = true;
//The mode of payment
bool public compensation = true;
//Address smart contract first draft Wallie
address first_project_addr = 0xC0B52b76055C392D67392622AE7737cdb6D42133;
//Start time
uint256 public start_time;
//Current day
uint256 current_day;
//Launch day
uint256 start_day;
//Deposit amount per day
uint256 daily_invest_to_contract;
//The address of the owner
address private adm_addr;
//Starting block
uint256 public start_block;
//Project started
bool public is_started = false;
//Statistics
//All investors
uint256 private all_invest_users_count = 0;
//Just introduced to the fund
uint256 private all_invest = 0;
//Total withdrawn from the fund
uint256 private all_payments = 0;
//The last address of the depositor
address private last_invest_addr = 0;
//The amount of the last contribution
uint256 private last_invest_amount = 0;
using SafeMath for uint;
using ToAddress for *;
using Zero for *;
constructor() public {
adm_addr = msg.sender;
current_day = 0;
daily_invest_to_contract = 0;
}
//Current time
function getTime() public view returns (uint256) {
return (now);
}
//The creation of the account of the investor
function createInvestor(address addr,address referer) private {
investors[addr].addr = addr;
if (investors[addr].referer.isZero()) {
investors[addr].referer = referer;
}
all_invest_users_count++;
emit NewInvestor(addr, msg.value);
}
//Check if there is an investor account
function checkInvestor(address addr) public view returns (bool) {
if (investors[addr].addr.isZero()) {
return false;
}
else {
return true;
}
}
//Accrual of referral bonuses to the participant
function setRefererBonus(address addr, uint256 amount, uint256 level_percent, uint256 level_num) private {
if (addr.notZero()) {
uint256 revenue = amount.mul(level_percent).div(100);
if (!checkInvestor(addr)) {
createInvestor(addr, address(0));
}
investors[addr].referals_profit = investors[addr].referals_profit.add(revenue);
investors[addr].referals_profit_balance = investors[addr].referals_profit_balance.add(revenue);
emit RefererBonus(msg.sender, addr, amount, revenue, level_num);
}
}
//Accrual of referral bonuses to participants
function setAllRefererBonus(address addr, uint256 amount) private {
address ref_addr_level_1 = investors[addr].referer;
address ref_addr_level_2 = investors[ref_addr_level_1].referer;
address ref_addr_level_3 = investors[ref_addr_level_2].referer;
setRefererBonus (ref_addr_level_1, amount, ref_bonus_level_1, 1);
setRefererBonus (ref_addr_level_2, amount, ref_bonus_level_2, 2);
setRefererBonus (ref_addr_level_3, amount, ref_bonus_level_3, 3);
}
//Get the number of dividends
function calcDivedents (address addr) public view returns (uint256) {
uint256 current_perc = 0;
if (address(this).balance < 2000 ether) {
current_perc = dividends_perc_before_2000eth;
}
else {
current_perc = dividends_perc_after_2000eth;
}
return investors[addr].investment.mul(current_perc).div(1000).mul(now.sub(investors[addr].investment_time)).div(1 days);
}
//We transfer dividends to the participant's account
function setDivedents(address addr) private returns (uint256) {
investors[addr].investment_profit_balance = investors[addr].investment_profit_balance.add(calcDivedents(addr));
}
//We enroll the deposit
function setAmount(address addr, uint256 amount) private {
investors[addr].investment = investors[addr].investment.add(amount);
investors[addr].investment_time = now;
all_invest = all_invest.add(amount);
last_invest_addr = addr;
last_invest_amount = amount;
emit NewInvestment(addr,amount);
}
//Cashback enrollment
function setCashBackBonus(address addr, uint256 amount) private {
if (investors[addr].referer.notZero() && investors[addr].investment == 0) {
investors[addr].cashback_profit_balance = amount.mul(cashback_bonus).div(100);
investors[addr].cashback_profit = investors[addr].cashback_profit.add(investors[addr].cashback_profit_balance);
emit CashbackBonus(addr, amount, investors[addr].cashback_profit_balance);
}
}
//Income payment
function withdraw_revenue(address addr) private {
uint256 withdraw_amount = calcDivedents(addr);
if (check_x2_profit(addr,withdraw_amount) == true) {
withdraw_amount = 0;
}
if (withdraw_amount > 0) {
investors[addr].investment_profit = investors[addr].investment_profit.add(withdraw_amount);
}
withdraw_amount = withdraw_amount.add(investors[addr].investment_profit_balance).add(investors[addr].referals_profit_balance).add(investors[addr].cashback_profit_balance);
if (withdraw_amount > 0) {
clear_balance(addr);
all_payments = all_payments.add(withdraw_amount);
emit NewWithdraw(addr, withdraw_amount);
emit ChangeBalance(address(this).balance.sub(withdraw_amount));
addr.transfer(withdraw_amount);
}
}
//Reset user balances
function clear_balance(address addr) private {
investors[addr].investment_profit_balance = 0;
investors[addr].referals_profit_balance = 0;
investors[addr].cashback_profit_balance = 0;
investors[addr].investment_time = now;
}
//Checking the x2 profit
function check_x2_profit(address addr, uint256 dividends) private returns(bool) {
if (investors[addr].investment_profit.add(dividends) > investors[addr].investment.mul(2)) {
investors[addr].investment_profit_balance = investors[addr].investment.mul(2).sub(investors[addr].investment_profit);
investors[addr].investment = 0;
investors[addr].investment_profit = 0;
investors[addr].investment_first_time_in_day = 0;
investors[addr].investment_time = 0;
return true;
}
else {
return false;
}
}
function() public payable
isStarted
rerfererVerification
isBlockInvestments
minInvest
allowInvestFirstThreeDays
setDailyInvestContract
setDailyInvest
maxInvestPerUser
maxDailyInvestPerContract
setAdvertisingComiss {
if (msg.value == 0) {
//Request available payment
withdraw_revenue(msg.sender);
}
else
{
//Contribution
address ref_addr = msg.data.toAddr();
//Check if there is an account
if (!checkInvestor(msg.sender)) {
//Создаем аккаунт пользователя
createInvestor(msg.sender,ref_addr);
}
//Transfer of dividends on Deposit
setDivedents(msg.sender);
//Accrual of cashback
setCashBackBonus(msg.sender, msg.value);
//Deposit enrollment
setAmount(msg.sender, msg.value);
//Crediting bonuses to referrers
setAllRefererBonus(msg.sender, msg.value);
}
}
//Current day
function today() public view returns (uint256) {
return now.div(1 days);
}
//Prevent accepting deposits
function BlockInvestments() public onlyOwner {
block_investments = true;
}
//To accept deposits
function AllowInvestments() public onlyOwner {
block_investments = false;
}
//Disable compensation mode
function DisableCompensation() public onlyOwner {
compensation = false;
}
//Run the project
function StartProject() public onlyOwner {
require(is_started == false, "Project is started");
block_investments = false;
start_block = block.number;
start_time = now;
start_day = today();
is_started = true;
}
//Investor account statistics
function getInvestorInfo(address addr) public view returns (address, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
Investor memory investor_info = investors[addr];
return (investor_info.referer,
investor_info.investment,
investor_info.investment_time,
investor_info.investment_first_time_in_day,
investor_info.investments_daily,
investor_info.investment_profit,
investor_info.referals_profit,
investor_info.cashback_profit,
investor_info.investment_profit_balance,
investor_info.referals_profit_balance,
investor_info.cashback_profit_balance);
}
//The stats for the site
function getWebStats() public view returns (uint256,uint256,uint256,uint256,address,uint256){
return (all_invest_users_count,address(this).balance,all_invest,all_payments,last_invest_addr,last_invest_amount);
}
//Check the start of the project
modifier isStarted() {
require(is_started == true, "Project not started");
_;
}
//Checking deposit block
modifier isBlockInvestments()
{
if (msg.value > 0) {
require(block_investments == false, "investments is blocked");
}
_;
}
//Counting the number of user deposits per day
modifier setDailyInvest() {
if (now.sub(investors[msg.sender].investment_first_time_in_day) < 1 days) {
investors[msg.sender].investments_daily = investors[msg.sender].investments_daily.add(msg.value);
}
else {
investors[msg.sender].investments_daily = msg.value;
investors[msg.sender].investment_first_time_in_day = now;
}
_;
}
//The maximum amount of contributions a user per day
modifier maxInvestPerUser() {
if (now.sub(start_time) <= 30 days) {
require(investors[msg.sender].investments_daily <= 20 ether, "max payment must be <= 20 ETH");
}
else{
require(investors[msg.sender].investments_daily <= 50 ether, "max payment must be <= 50 ETH");
}
_;
}
//Maximum amount of all deposits per day
modifier maxDailyInvestPerContract() {
if (now.sub(start_time) <= 30 days) {
require(daily_invest_to_contract <= contract_daily_limit, "all daily invest to contract must be <= 100 ETH");
}
_;
}
//Minimum deposit amount
modifier minInvest() {
require(msg.value == 0 || msg.value >= min_invesment, "amount must be = 0 ETH or > 0.01 ETH");
_;
}
//Calculation of the total number of deposits per day
modifier setDailyInvestContract() {
uint256 day = today();
if (current_day == day) {
daily_invest_to_contract = daily_invest_to_contract.add(msg.value);
}
else {
daily_invest_to_contract = msg.value;
current_day = day;
}
_;
}
//Permission for users of the previous project whose payments were <= 30% to make a contribution in the first 3 days
modifier allowInvestFirstThreeDays() {
if (now.sub(start_time) <= 3 days && compensation == true) {
uint256 invested = WallieFirstProject(first_project_addr).invested(msg.sender);
require(invested > 0, "invested first contract must be > 0");
uint256 payments = WallieFirstProject(first_project_addr).payments(msg.sender);
uint256 payments_perc = payments.mul(100).div(invested);
require(payments_perc <= 30, "payments first contract must be <= 30%");
}
_;
}
//Verify the date field
modifier rerfererVerification() {
address ref_addr = msg.data.toAddr();
if (ref_addr.notZero()) {
require(msg.sender != ref_addr, "referer must be != msg.sender");
require(investors[ref_addr].referer != msg.sender, "referer must be != msg.sender");
}
_;
}
//Only the owner
modifier onlyOwner() {
require(msg.sender == adm_addr,"onlyOwner!");
_;
}
//Payment of remuneration for advertising
modifier setAdvertisingComiss() {
if (msg.sender != adm_addr && msg.value > 0) {
investors[adm_addr].referals_profit_balance = investors[adm_addr].referals_profit_balance.add(msg.value.mul(advertising_fees).div(100));
}
_;
}
}
//The interface of the first draft (the amount of deposits and amount of payments)
contract WallieFirstProject {
mapping (address => uint256) public invested;
mapping (address => uint256) public payments;
}
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;
}
}
library ToAddress
{
function toAddr(uint source) internal pure returns(address) {
return address(source);
}
function toAddr(bytes source) internal pure returns(address addr) {
assembly { addr := mload(add(source,0x14)) }
return addr;
}
}
library Zero
{
function requireNotZero(uint a) internal pure {
require(a != 0, "require not zero");
}
function requireNotZero(address addr) internal pure {
require(addr != address(0), "require not zero address");
}
function notZero(address addr) internal pure returns(bool) {
return !(addr == address(0));
}
function isZero(address addr) internal pure returns(bool) {
return addr == address(0);
}
} | Payment of remuneration for advertising | modifier setAdvertisingComiss() {
if (msg.sender != adm_addr && msg.value > 0) {
investors[adm_addr].referals_profit_balance = investors[adm_addr].referals_profit_balance.add(msg.value.mul(advertising_fees).div(100));
}
_;
}
| 12,587,630 | [
1,
6032,
434,
849,
318,
7067,
364,
16738,
13734,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
202,
20597,
444,
1871,
1097,
13734,
799,
1054,
1435,
288,
203,
202,
202,
430,
261,
3576,
18,
15330,
480,
31003,
67,
4793,
597,
1234,
18,
1132,
405,
374,
13,
288,
203,
1082,
202,
5768,
395,
1383,
63,
20864,
67,
4793,
8009,
266,
586,
1031,
67,
685,
7216,
67,
12296,
273,
2198,
395,
1383,
63,
20864,
67,
4793,
8009,
266,
586,
1031,
67,
685,
7216,
67,
12296,
18,
1289,
12,
3576,
18,
1132,
18,
16411,
12,
361,
1097,
13734,
67,
3030,
281,
2934,
2892,
12,
6625,
10019,
203,
202,
202,
97,
203,
202,
202,
67,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
facts сущ_предл_сущ language=Russian
{
arity=3
return=boolean
generic
}
#region Предлог_В
// -------------------------- ПРЕДЛОГ 'В' -----------------------------------
// для существительных с семантикой перемещения допускается присоединение 'в' с винительным падежом.
wordentry_set сущ_движения_для_в=
{
//существительное:доступ{}, // Как я могу получить доступ в учётную запись для ИП
существительное:игра{}, // Есть поле для игры в мини-футбол.
существительное:введение{}, // Я впустил его внутрь и произвел необходимые действия для его введения в должность второго пилота
существительное:направление{}, // Как получить направление в детский сад?
существительное:отдача{}, // Ему грозила отдача в психиатрическую лечебницу.
существительное:бегство{}, // Ее хватило для бегства в Швейцарию.
существительное:жалоба{}, // Так появилась жалоба в контрольно-ревизионное управление.
существительное:царапанье{}, // Но царапанье в дверь не прекратилось. (ЦАРАПАНЬЕ В ДВЕРЬ)
существительное:оглядка{}, // Правительство работает без оглядки на какое-то второе лицо.
существительное:внесение{}, // Создатель мельдония объяснил внесение препарата в список запрещенных
существительное:прием{}, // О приеме новых членов в комсомол говорил Саша Корнаков.
существительное:пострижение{}, // При пострижении в монашество переименовывают человека.
существительное:сошествие{}, // По сошествии в ад Он воскрес
существительное:вера{ одуш:неодуш }, // Вера в лен звучит в нем.
существительное:вызов{}, // Ждем вызова в Московский комитет партии.
существительное:игрок{}, // Игроки в демократию оказались одни и те же.
существительное:миграция{}, // Наблюдается активная миграция молодежи в различные уголки страны.
существительное:инвестирование{}, // Премьер Абхазии дорабатывает в Москве вопросы инвестирования в республику
существительное:вмешательство{}, // Предварительное расследование пока исключает вмешательство членов экипажа в работу системы пожаротушения.
существительное:выезд{}, // В случае выезда в другие регионы могут возникнуть проблемы.
существительное:сдача{}, // Сдача трубопровода в эксплуатацию переносится на более поздний срок.
существительное:вхождение{}, // Это было одним из условий вхождения Литвы в Евросоюз.
существительное:пропуск{}, // Надо оформлять пропуска в закрытую зону, изучать анкеты
существительное:наблюдение{}, // При любительских наблюдениях в бинокль или телескоп также следует использовать затемняющий светофильтр, помещённый перед объективом.
существительное:захват{},
существительное:взятие{},
существительное:путь{}, // Она описала путь в свою комнату. (ПУТЬ)
существительное:ОБРАЩЕНИЕ{}, // В 1229 году Немецкий Орден начал завоевание Пруссии для обращения в христианство прибалтийских язычников и подготовки немецкой колонизации. (ОБРАЩЕНИЕ)
существительное:ДОСТУП{}, // Одетым в перчатку правым кулаком он разбил окно, давшее ему доступ в комнату отдыха. (ДОСТУП)
существительное:рост{}, // рост производства в два раза (СУЩ+В+вин.доп.сокращение, увеличение)
существительное:падение{},
существительное:марш{}, // В Москве начинается «марш в защиту детей»
существительное:вторжение{}, // вторжение в Сирию не планируется (ВТОРЖЕНИЕ)
существительное:интервенция{}, // Британия отказалась от "гуманитарной интервенции" в Сирию
существительное:ПОПРАВКА{}, // Парламент Венгрии утвердил поправки в Конституцию, ослабляющие демократию в стране (ПОПРАВКА)
существительное:ИНВЕСТИЦИЯ{}, // Минфин предлагает освободить от налогов долгосрочные инвестиции физлиц в ценные бумаги (ИНВЕСТИЦИЯ)
существительное:ВВОД{}, // нарушают сроки оформления документации и ввода месторождений в эксплуатацию (ВВОД)
существительное:ВЫСТРЕЛ{}, // Он был убит выстрелом в затылок (ВЫСТРЕЛ)
существительное:УХОД{}, // Р.Кастро не исключает ухода в отставку по причине возраста (УХОД)
существительное:ВИЗА{}, // Россиянам усложнили получение виз в Тайвань (ВИЗА)
существительное:ДВЕРЬ{}, // передо мной была широко открытая дверь во двор (ДВЕРЬ)
существительное:удар{}, // нанес жертве решающий удар в живот
существительное:доставление{}, // В соответствии со своими должностными обязанностями милиционер комендантского отделения был обязан доложить о факте задержания и доставления курсанта в опорный пункт милиции
существительное:употребление{}, // употребление поддельных сухариков в пищу может повлечь пищевое отравление (УПОТРЕБЛЕНИЕ В)
существительное:РАНЕНИЕ{}, // судья , получившая огнестрельное ранение в живот (РАНЕНИЕ В вин)
существительное:ОТЧИСЛЕНИЕ{}, // из его зарплаты производятся отчисления в пользу дочери (ОТЧИСЛЕНИЯ В)
существительное:ТРУДОУСТРОЙСТВО{}, // письменное направление для трудоустройства в общество с ограниченной ответственностью (ТРУДОУСТРОЙСТВО В вин)
существительное:ОБЪЕДИНЕНИЕ{}, // получение политической власти и достижение сугубо политических целей не является основным мотивом объединения в данные группы и организации (ОБЪЕДИНЕНИЕ В вин)
существительное:капиталовложение{}, // Главная проблема Америки – низкий уровень капиталовложений в экономику!
существительное:звонок{}, // Экономьте на звонках в другие города и страны (ЗВОНОК В)
существительное:проход{}, // После выполнения финальной миссии можно найти проход в секретную зону последнего уровня. (ПРОХОД В)
существительное:попадание{}, // Минимальный зазор между крышкой и пиалой обеспечивает сохранение аромата чая и предотвращает попадание чаинок в питьевую чашку (ПОПАДАНИЕ В)
существительное:врата{}, // Каждый эпизод игрок начинает на футуристической военной базе, в которой присутствуют врата в альтернативную реальность (ВРАТА В)
существительное:выбор{}, // Когда проводятся выборы в сенат? (ВЫБОРЫ В)
существительное:внедрение{}, // внедрение достижений науки в производство (внедрение в)
существительное:возвращение{}, // возвращение блудного сына в отчий дом (возвращение в)
существительное:запуск{}, // запуск в экусплуатацию
существительное:постановка{}, // постановка судна в док
существительное:выход{}, // готовить для выхода в свет
существительное:проникновение{}, // воспрепятствовать проникновению в закрытое помещение
существительное:полёт{}, // полет в неизвестность
существительное:поступление{}, // Поступление в докторантуру университета
существительное:сбор{}, // Он давно кончил все свои сборы в дорогу.
существительное:кандидат{}, // Председатель предложил назвать кандидатов в комиссию.
существительное:вступление{}, // указ о вступлении в силу
существительное:изменение{}, // тенденция к изменению в худшую сторону
существительное:вклад{}, // присуждаться за весомый вклад в исследования рака
существительное:поездка{},
существительное:поход{},
существительное:путешествие{},
существительное:перемещение{},
существительное:визит{},
существительное:отправка{},
существительное:транспортировка{},
существительное:перевод{},
существительное:эмиграция{},
существительное:иммиграция{},
существительное:передача{},
существительное:дорога{}, // Я не знаю дороги в эту деревню.
существительное:поставка{}, // Россия сняла эмбарго на поставки оружия в Ливию
существительное:абонемент{}, // Я купил абонемент в оперу.
существительное:путевка{}, // Я достал путёвки в санаторий.
существительное:вход{}, // Я буду ждать вас у входа в музей.
существительное:оборот{}, // Этот мотор делает 600 оборотов в минуту.
существительное:превращение{}, // превращение куколки в бабочку
существительное:стук{}, // Раздаётся стук в дверь.
существительное:билет{}, // Мы купили билеты в цирк.
существительное:подача{}, // подача воды в определённые часы
существительное:явка{}, // явка в суд
существительное:переход{}, // переход в другую веру
существительное:доставка{}, // Другие говорили, что солдатам нельзя доверять доставку пленников в столицу.
существительное:приведение{} // приведение в исполнение
}
//ткань, ткань в полоску
//три урожая в год
// Путешествие в Москву
fact сущ_предл_сущ
{
if context { сущ_движения_для_в предлог:в{} существительное:*{ одуш:неодуш падеж:вин } }
then return true
}
// путешествие в Ixtlan
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 false
}
*/
// Предлог 'в' c предложным падежом всегда присоединяется к любым существительным
// Питательные элементы в ягодах легко усваиваются
// Кот в сапогах
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:в{} существительное:*{ одуш:неодуш падеж:предл } }
then return true
}
// Хлопнет калитка в саду
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:в{} существительное:*{ одуш:неодуш падеж:мест } }
then return true
}
// тёмные ночи в период майских дождей
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:в{} существительное:период{ падеж:вин } }
then return true
}
wordentry_set Сущ_В_Предл=существительное:{
убеждение, // ипохондрический бред — убеждение больного в наличии у него какого-то заболевания
работа, // Эти устройства неприспособлены к работе в жару
содержание, // Фрукты и ягоды особенно полезны организму благодаря содержанию в них витаминов, органических кислот и минеральных солей. (СОДЕРЖАНИЕ В)
специалист, // Эта программа была разработана при участии известных специалистов в области экономики. (СПЕЦИАЛИСТ В)
расчет, // Европа стала второй оффшорной зоной для расчетов в юанях
участие, // Приглашаем всех желающих принять участие в работе над статьями
штраф, // денежный штраф в размере 50 рублей
уверенность, // У меня нет уверенности в успехе.
успех, // успех в жизни
совещание, // совещание в верхах
понижение, // понижение в должности
дело // рассмотрение дела в последней инстанции
}
fact сущ_предл_сущ
{
if context { Сущ_В_Предл предлог:в{} *:*{ падеж:предл } }
then return true
}
wordentry_set Сущ_В_Им=существительное:{
кандидат
}
// Некоторые существительные могут прикреплять В + им.п.:
// кандидат в президенты
fact сущ_предл_сущ
{
if context { Сущ_В_Им предлог:в{} *:*{ падеж:им } }
then return true
}
// По умолчанию запретим связывание предлога В для существительных.
// То есть для всех остальных случаев предлог 'в' прикрепляется к глаголу:
// Питательные элементы в ягодах легко усваиваются
fact сущ_предл_сущ
{
if context { * предлог:в{} *:*{ падеж:предл } }
then return false,-4
}
fact сущ_предл_сущ
{
if context { * предлог:в{} * }
then return false,-6
}
#endregion Предлог_В
#region Предлог_ПОД
// ----------------------- ПРЕДЛОГ 'ПОД' ------------------------------
// снял запрет, чтобы разбирать:
// земля под ним горела
// ^^^^^^^
fact сущ_предл_сущ
{
if context { * предлог:под{} *:*{ падеж:твор } }
then return true
}
wordentry_set Сущ_ПОД_Вин=существительное:{
заключение // Решается вопрос об избрании ему меры пресечения в виде заключения под стражу.
}
fact сущ_предл_сущ
{
if context { Сущ_ПОД_Вин предлог:под{} *:*{ падеж:вин } }
then return true
}
fact сущ_предл_сущ
{
if context { * предлог:под{} *:*{ падеж:вин } }
then return false,-8
}
// По умолчанию запрещаем связывание сущ. с предлогом ПОД:
// мой руки с дезинфецирующим мылом под струёй тёплой воды
fact сущ_предл_сущ
{
if context { * предлог:под{} * }
then return false,-5
}
#endregion Предлог_ПОД
#region Предлог_ПРО
// ----------------------- ПРЕДЛОГ 'ПРО' ------------------------------
wordentry_set Сущ_Про_Вин=существительное:{
книга,// книга про пиратов
рассказ,
история,
роман,
фильм
}
// книга про пиратов
fact сущ_предл_сущ
{
if context { Сущ_Про_Вин предлог:про{} * }
then return true
}
// я рассказываю детям про пиратов
fact сущ_предл_сущ
{
if context { существительное:*{ одуш:одуш } предлог:про{} * }
then return false,-10
}
#endregion Предлог_ПОД
#region Предлог_ОБ
// ----------------------- ПРЕДЛОГ 'ОБ' ------------------------------
wordentry_set Сущ_ОБ_Предл=существительное:{
учение, // В этике развил учение об атараксии.
воспоминание, // При воспоминании об этом Милли расхохоталась.
приказ, // неподчинение приказу об остановке судна
требование, // Требование правообладателя об удалении контента
резолюция, // Британский парламент отклонил правительственную резолюцию об основаниях для военной интервенции в Сирию
письмо, // Директор фирмы написала клиентам гарантийные письма об обязательстве возврата денег
данные, // НАТО не опубликует данные об атаках талибов в Афганистане (ДАННЫЕ)
мысль, // одна мысль об этом казалась мне чудовищной (МЫСЛЬ)
легенда, // А легенда об убийце органистки жила.
расследование, // Шесть европейских стран начинают расследование об отмывании нелегальных российских денег
законопроект, // Правительство одобрило законопроект об ускоренной постановке на налоговый учёт иностранцев или лиц без гражданства
МНЕНИЕ, // он выразил мнение об ожидаемом положительном эффекте от решения правительства докапитализировать банки (МНЕНИЕ ОБ)
РЕШЕНИЕ, // США приняли решение об ужесточении экономических санкций против Ирана (РЕШЕНИЕ ОБ)
ИНФОРМАЦИЯ, // получаю информацию обо всех игроках (ИНФОРМАЦИЯ ОБ)
ВОПРОС, // решается вопрос об избрании меры пресечения (ВОПРОС ОБ)
ДОГОВОР, // Россия пока не видит возможности для возобновления переговоров по Договору об обычных вооруженных силах в Европе (ДОГОВОР ОБ)
слух, // слух об их приближении летел впереди. (СЛУХ ОБ)
представление, // эти факты опровергают представления об устройстве Вселенной
размышление,
сообщение, // закидывать сообщениями об ошибках
рассказ, // крайне забавный рассказ об очень толстой кошке, мирно спящей на мягком кожаном диване
скорбь, // его скорбь об умершем животном вызывала острое сочувствие
история,
байка,
заявление, // заявление об отставке
дело, // Небольшое дело об убийстве
кодекс,
закон,
память, // Сохраните это на память обо мне.
упоминание // Поищи у коллеги упоминание об этом инциденте
}
fact сущ_предл_сущ
{
if context { Сущ_ОБ_Предл предлог:об{} *:*{ падеж:предл } }
then return true
}
fact сущ_предл_сущ
{
if context { Сущ_ОБ_Предл предлог:об{} @regex("[a-z]+[0-9]*") }
then return true
}
wordentry_set Сущ_ОБ_Вин=существительное:{
удар // раздался глухой удар клинка об пол.
}
fact сущ_предл_сущ
{
if context { Сущ_ОБ_Вин предлог:об{} *:*{ падеж:вин } }
then return true
}
// По умолчанию закроем связывание с предлогом ОБ
// Поищи упоминание у коллеги об этом инциденте
fact сущ_предл_сущ
{
if context { * предлог:об{} * }
then return false,-5
}
#endregion Предлог_ОБ
#region Предлог_С
// --------------------- ПРЕДЛОГ 'С' --------------------------------
// Обычно существительные нормально связываются с предлогом С, за исключением
// случаев, которые мы перечислим явно.
wordentry_set Запрет_Сущ_С=существительное:{
рука
}
fact сущ_предл_сущ
{
if context { Запрет_Сущ_С предлог:с{} * }
then return false
}
// По умолчанию запрещаем связывание сущ+С+вин.п.
// взгляд со стороны
fact сущ_предл_сущ
{
if context { *:*{} предлог:с{} *:*{ падеж:вин } }
then return false,-5
}
#endregion Предлог_С
#region Предлог_ПОСЛЕ
// ---------------------- ПРЕДЛОГ 'ПОСЛЕ' ---------------
// Пейзаж после битвы
fact сущ_предл_сущ
{
if context { существительное:пейзаж{} предлог:после{} *:*{ падеж:род } }
then return true
}
// Коль, купи молока после работы
fact сущ_предл_сущ
{
if context { * предлог:после{} * }
then return false,-5
}
#endregion Предлог_ПОСЛЕ
#region Предлог_ПРЕЖДЕ
// ---------------------- ПРЕДЛОГ 'ПРЕЖДЕ' ---------------
// Он принёс деньги прежде срока.
fact сущ_предл_сущ
{
if context { * предлог:прежде{} * }
then return false,-10
}
#endregion Предлог_ПРЕЖДЕ
#region Предлог_НА
// ---------------------- ПРЕДЛОГ 'НА' ---------------
// В редких случаях может быть связывание с НА+предл. падеж
wordentry_set Сущ_НА_Предл=существительное:{
заявление, // Заявление на материнский капитал оформляется в органах Пенсионного фонда по месту жительства.
проводы, // Ежегодно устраиваются торжественные проводы на пенсию.
пересадка, // В Москве предстоит пересадка на Сочи.
испытание, // Начинаются испытания стволовых клеток на людях
ПОЕДИНОК, // но была большая разница между поединком на рапирах и грязной поножовщиной без всяких правил
СОБЫТИЕ, // События на Кипре - сигнал большой опасности для России. (СОБЫТИЕ)
БЕЗОПАСНОСТЬ, // NASA усиливает безопасность на своих объектах (БЕЗОПАСНОСТЬ)
ЕЗДА, // снаряжение для езды на лошади (ЕЗДА)
наличие, // Доказательство наличия подповерхностного океана на Европе
проверка, // Чиновников отстранили от госзаказа после проверки на полиграфе
СЛУЖБА, // Служба на каникулах помешает учебному процессу (СЛУЖБА)
ПЯТНО, // Гигантское пятно на Солнце может привести к солнечным бурям (ПЯТНО)
ПОРЯДОК, // По мнению руководителя администрации города , продление сроков операции позволит , во-первых , навести порядок на рынке пиротехники (ПОРЯДОК НА предл)
ВОЗРОЖДЕНИЕ, // Общественная оборона — это возрождение идеи и практики земства на новом уровне развития русского общества (ВОЗРОЖДЕНИЕ НА)
АВАРИЯ, // Я очень сожалею , что произошла авария на одной из наших шахт (АВАРИЯ)
ПОЗИЦИЯ, // Политик пояснил , что различные страны продолжают осуществлять политику по укреплению своих позиций на Южном Кавказе (ПОЗИЦИЯ НА)
ГОЛОСОВАНИЕ, // Мне также довелось отслеживать процесс голосования на избирательном участке , расположенном на территории исправительной колонии (ГОЛОСОВАНИЕ НА предл)
ГИБЕЛЬ, // В Москве проводится проверка по факту гибели людей на железнодорожных путях (ГИБЕЛЬ НА)
давка, // Снегопад парализовал Москву и привёл к давке на некоторых станциях столичного метро (давка на)
интервенция, // Они даже рассматривали военные интервенции на Ближнем Востоке как способ что-то изменить (ИНТЕРВЕНЦИЯ НА предл)
покров, // Почему у человека редуцировался волосяной покров на теле? (ПОКРОВ НА)
убийство, // Он совершил убийство на почве ревности. (УБИЙСТВО НА ПОЧВЕ ...)
поездка, // Москвичей призывают воздержаться от поездок на личных автомобилях. (ПОЕЗДКА НА чем-то)
проблема, // Вслед за Западной Украиной проблемы на дорогах начались в восточных областях (проблема на)
поражение, // Лидер оппозиции Южной Кореи признал поражение на выборах. (ПОРАЖЕНИЕ НА)
ситуация, // Два министерства по-разному оценивают ситуацию на дорогах в западных областях (СИТУАЦИЯ НА)
опыт, // Опыты на крысах показали, что употребление сахара вызывает зависимость (ОПЫТ НА)
взрыв, // Взрыв на мясокомбинате в Мордовии (ВЗРЫВ НА)
катастрофа, // все помнят ту катастрофу на комбинате (КАТАСТРОФА НА)
операция, // Ему сделали операцию на сердце. (ОПЕРАЦИЯ НА)
торг, // возобновление торгов на бирже (торг на)
напряжение, // регулировать напряжением на базе
игра, // обучиться игре на скрипке
оглавление, // книга с картинками и оглавлением на иностранном языке
пожар, // пожар на фабрике огнетушителей
доля, // Банки увеличивают свою долю на рынке пластиковых карт.
присутствие, // Мелкие банки усиливают свое присутствие на рынке розничного кредитования.
обстановка, // Обстановка на дороге осложнена густым туманом.
трагедия, // трагедия на авиашоу
программирование, // прослушать учебный курс по программированию на функциональных языках
работа, // работа на стройках коммунизма
изображение, // четкое изображение на экране
случай, // С ним произошел несчастный случай на охоте
выступление, // Это было моё первое выступление на сцене.
применение, // Эта теория находит широкое применение на практике.
дело, // Дела на фронте поправляются.
преподавание, // в вузы можно вернуть преподавание на русском языке
исчезновение, // Исчезновение на 7-ой улице
трещина, // трещины на коже
торговля, // стандарт для торговли на лондонской бирже металла
сандалия // соломенные сандалии на верёвочной подошве
}
fact сущ_предл_сущ
{
if context { Сущ_НА_Предл предлог:на{} *:*{падеж:предл} }
then return true
}
fact сущ_предл_сущ
{
if context { Сущ_НА_Предл предлог:на{} *:*{падеж:мест} }
then return true
}
/*
// лицо на фотографии
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:на{} существительное:фотография{падеж:предл} }
then return true
}
*/
// просмотр на youtube
fact сущ_предл_сущ
{
if context { Сущ_НА_Предл предлог:на{} @regex("[a-z]+[0-9]*") }
then return true
}
/*
// крупная туманность на ночном небе
fact сущ_предл_сущ
{
if context { существительное:туманность{} предлог:на{} существительное:небо{падеж:предл} }
then return true
}
*/
wordentry_set Сущ_НА_Вин=существительное:{
ассигнование, // Из года в год увеличиваются ассигнования на оборону
опоздание, // Составлен рейтинг самых популярных причин опоздания на работу
гнев, // Ее внезапно охватил гнев на себя.
квота, // ПРАВИТЕЛЬСТВО УВЕЛИЧИТ КВОТЫ НА ИМПОРТ МЯСА (КВОТЫ НА ИМПОРТ МЯСА)
кандидат, // Нарушитель становится верным кандидатом на банкротство. (КАНДИДАТ НА ...)
документ, // Документы на товар у коммерсантов отсутствовали. (ДОКУМЕНТЫ НА ТОВАР)
путевка, // Сборная России выиграла путевку на Олимпиаду. (ПУТЕВКУ НА)
бремя, // Налоговое бремя на электроэнергетику не изменилось. (БРЕМЯ НА)
навал, // Мощный порог кончался навалом на скалы. (НАВАЛ НА)
предписание, // Были выданы предписания на устранение нарушений. (ПРЕДПИСАНИЕ НА УСТРАНЕНИЕ)
настрой, // твердый настрой на победу
намек, // В голосе слышался намек на иронию.
позыв, // При этом бывает внезапный позыв на мочу.
действие, // Теперь о действии Фосфорной кислоты на кости.
патент, // ФАС предложила игнорировать зарубежные патенты на лекарства
пародия, // Участники акции представили пародии на проекты здания небоскреба.
возвращение, // По возвращении на родину участвовал в разгроме Колчака.
дверь, // Дверь на сушу, кажется, открыта.
распоряжение, // Передайте в полки распоряжение на подготовку к перебазированию.
лицензия, // Большинство архангельских больниц не имеют лицензию на переливание крови
деление, // Система предусматривает деление маршрутной карты города на 62 лота.
воздействие, // Компании-разработчику предстоит ликвидировать последствия техногенных воздействий на окружающую среду.
отчисление, // Современное законодательство ликвидировало компенсационные отчисления на воспроизводство минерально-сырьевой базы.
приглашение, // Всем им были разосланы повестки с приглашением на заседание.
тендер, // Продолжается подготовка к проведению международного тендера на строительство АЭС.
выдвижение, // В Абазе завершилось выдвижение кандидатов на должность главы города
поправка, // При наблюдении звезд необходимо сделать поправку на аберрацию.
время, // У нас почти не было времени на осмотр дворца. (ВРЕМЯ)
обмен, // По этому пути огромные фургоны везли оружие и прочие товары, предназначенные для обмена на меха, шкуры, травы, слоновую кость и клыки (ОБМЕН)
вход, // Они стали входом на сцену (ВХОД)
экспорт, // Белоруссия увеличила свой экспорт в Россию
допуск,
ПЕРЕХОД, // Сирийская оппозиция сообщила о переходе на ее сторону генерала сирийской армии (ПЕРЕХОД)
ДОРОГА, // Прохожий спросил у меня дорогу на станцию (ДОРОГА)
ОХОТНИК, // У «Охотников на ведьм» появится продолжение (ОХОТНИК)
СУБСИДИЯ, // Д.Медведев утвердил распределение по регионам субсидий на медицинскую помощь (СУБСИДИЯ)
ПОДЪЕМ, // Подъём на гору продолжался два часа (ПОДЪЕМ)
мораторий, // Кремль снял мораторий на замену "слабых губернаторов"
план, // США раздражены планами Пакистана на иранский газ (ПЛАН)
отправка, // Японский робот Kibo готовится к отправке на борт Международной космической станции (ОТПРАВКА)
РЕАКЦИЯ, // стереотипная реакция организма на внешние раздражения (РЕАКЦИЯ)
ЖАЛОБА, // США заблокировали жалобу России на теракт в Сирии (ЖАЛОБА)
КУРС, // Курс нового Советского правительства на индустриализацию страны позволил создать мощную промышленную базу, необходимую для полного перевооружения Красной Армии (КУРС)
ПОСТАНОВКА, // Правительство одобрило законопроект об ускоренной постановке на налоговый учёт иностранцев или лиц без гражданства (ПОСТАНОВКА НА)
ТЕСТИРОВАНИЕ, // Законопроект о тестировании школьников Москвы на наркотики доработают (ТЕСТИРОВАНИЕ НА вин)
ПОСТАВКА, // для поставок на экспорт (ПОСТАВКА НА)
ПРЕТЕНДЕНТ, // Отбор претендентов на участие в конкурсе будет осуществлять конкурсная комиссия (ПРЕТЕНДЕНТ НА)
УХОд, // Виталию не следует думать об уходе на покой (УХОд НА вин)
ПОКУШЕНИЕ, // Выборы президента Армении могут перенести из-за покушения на кандидата (ПОКУШЕНИЕ НА)
ТАРИФ, // Окончательное решение о правомочности установления тарифа на услуги по передаче электрической энергии для этой организации планируется принять в декабре (ТАРИФ НА)
РАЗРЕШЕНИЕ, // для получения разрешений на право передвижения по заповедной акватории (РАЗРЕШЕНИЕ НА)
СТАВКА, // Парфюмеры делают ставку на провокации и психологию (СТАВКА НА)
СОГЛАСИЕ, // Нигер дал согласие на размещение американских беспилотников (СОГЛАСИЕ НА)
АТАКА, // Власть собирается бороться с атаками на сайт Кремля (АТАКА НА)
КОНТРАКТ, // Россия приостановила контракт на закупку итальянских бронемашин (КОНТРАКТ НА что-то)
ДАВЛЕНИЕ, // искусственно заниженные цены и понижающее давление на производство (ДАВЛЕНИЕ НА)
ЗАПРЕТ, // В Молдавии введен запрет на амнистию или помилование педофилов. (ЗАПРЕТ НА)
выезд, // Совет Федерации уточнил ответственность за выезд на встречную полосу. (ВЫЕЗД НА)
вторжение, // В агонии демон разрушает ад, и вторжение на Землю прекращается. (ВТОРЖЕНИЕ НА)
путь, // Он завернул к нам по пути на работу.
СООБРАЖЕНИЕ, // У меня есть свои соображения на этот счет (СООБРАЖЕНИЕ НА)
компромат, // С.Митрохин опубликовал компромат на думских подельников Гудкова (компромат на)
ограничение, // государство ввело ограничения на свободу перемещения (ограничение на)
вид, // затем открылся вид на море (вид на)
вывод, // вывод войск на позиции (вывод на)
продвижение, // мы замедлили продвижение на Восток (продвижение на)
нажатие, // откидывать нажатием на кнопку
воззрение, // Воззрения на природу человека
взгляд, // наши взгляды на жизнь слишком сильно различаются
очередь, // очередь на регистрацию
нападение, // нападение на члена НАТО
просмотр, // будем использовать просмотр на один шаг вперед
падение, // падение на асфальт
ссылка, // ссылка на источники
пошлина, // пошлины на импорт
акциз, // акциз на алкоголь
доклад, // Он готовит доклад на эту тему.
поездка, // Мы совершили поездку на север.
налёт, // совершить налёт на банк
указание, // это было указание на тайный смысл.
ответ, // Ученик дал правильный ответ на вопрос учителя.
шанс, // У этого села были большие шансы на процветание
право, // Они заработали трудом право на отдых.
избрание, // избрание на третий срок
затрата, // затраты на организацию спектакля
билет, // мы купили билеты на фильм
налог, // налог на предметы роскоши
охота, // Охота на хищниц
расход, // расходы на воспитание детей
явка, // явка на работу
неявка, // Она оправдала неявку на занятия болезнью.
цена, // подписная цена на газету
повышение, // Рабочие бастуют, требуя повышения зарплаты на двадцать процентов.
понижение,
спрос, // Растёт спрос на товары.
направление, // Самолёт взял направление на юг.
средство, // Средства на народное образование отпускает государство.
влияние, // Теория имеет очень сильное влияние на практику.
эмбарго, // Россия сняла эмбарго на поставки оружия в Ливию
транспортировка, // транспортировка на склад
диплом, // У него не было диплома на звание врача.
посягательство, // посягательство на свободу слова
выход
}
fact сущ_предл_сущ
{
if context { Сущ_НА_Вин предлог:на{} *:*{падеж:вин} }
then return true
}
// небо на горизонте
fact сущ_предл_сущ
{
if context { существительное:небо{} предлог:на{} 'горизонте'{падеж:предл} }
then return true
}
// работа на Google
fact сущ_предл_сущ
{
if context { Сущ_НА_Вин предлог:на{} @regex("[a-z]+[0-9]*") }
then return true
}
/*
// запрет связывания магазин+на, хотя для улиц он должен быть отключен:
// купи молока в магазине на оставшиеся деньги
fact сущ_предл_сущ
{
if context { существительное:магазин{} предлог:на{} * }
then return false
}
*/
fact сущ_предл_сущ
{
if context { * предлог:на{} *:*{ падеж:предл } }
then return false,-4
}
fact сущ_предл_сущ
{
if context { * предлог:на{} *:*{ падеж:мест } }
then return false,-4
}
fact сущ_предл_сущ
{
if context { * предлог:на{} *:*{ падеж:вин } }
then return false,-5
}
fact сущ_предл_сущ
{
if context { * предлог:на{} * }
then return false
}
#endregion Предлог_НА
#region Предлог_ИЗ_ПОД
// ------------- ПРЕДЛОГ 'ИЗ-ПОД' -----------------------
// Он выдвинул чемодан из-под кровати.
fact сущ_предл_сущ
{
if context { * предлог:из-под{} * }
then return false,-5
}
#endregion Предлог_ИЗ_ПОД
#region Предлог_В_СВЯЗИ_С
// ------------- ПРЕДЛОГ 'В СВЯЗИ С' -----------------------
fact сущ_предл_сущ
{
if context { * предлог:в связи с{} * }
then return false,-10
}
#endregion Предлог_В_СВЯЗИ_С
#region Предлог_ЗА
// ------------------ ПРЕДЛОГ 'ЗА' -------------------------------
// похороны за счёт города
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:за{} существительное:счет{ падеж:вин } }
then return true
}
wordentry_set Сущ_ЗА_Вин=существительное:{
долг, // В течение августа планируется закрыть долги за июнь полностью.
опасение, // Но у него есть серьезные опасения за ее жизнь.
борьба, // это борьба за существование!
тяжба, // МИД обеспокоен тяжбой американских лесбиянок за российского ребенка
контроль, // контроль за безопасностью
очередь, // очередь за едой
"матч-реванш", // матч-реванш за звание
бой,
премия, // премия за выслугу лет
борец, // последовательный борец за что-либо
убыток, // убыток компании за последние шесть месяцев
цена, // цена за килограмм
отъезд, // отъезд за границу
вердикт, // Вердикт за деньги
око, // Око за око
счет, // Я получил счёт за телефон.
ответственность, // Я снимаю с себя всякую ответственность за его поведение.
плата, // плата за ночное дежурство
оплата // оплата за неделю
}
fact сущ_предл_сущ
{
if context { Сущ_ЗА_Вин предлог:за{} *:*{ падеж:вин } }
then return true
}
wordentry_set Сущ_ЗА_Твор=существительное:{
контроль, // полномочия по контролю за выполнением лицензионных требований
надзор, // надзор за соблюдением
очередь, // Он встал в очередь за мясом.
Охотник // Охотники за разумом
}
fact сущ_предл_сущ
{
if context { Сущ_ЗА_Твор предлог:за{} *:*{ падеж:твор } }
then return true
}
fact сущ_предл_сущ
{
if context { * предлог:за{} * }
then return false,-4
}
#endregion Предлог_ЗА
#region Предлог_ПО
// ---------------------- ПРЕДЛОГ 'ПО' -------------------------------
// По умолчанию подавим связывание для этого предлога.
// Шла Женя по дороге и сосала сушки
wordentry_set Сущ_ПО_Дат={
существительное:тренинг{}, // Воронежские выпускники пройдут тренинг по сдаче единого государственного экзамена
существительное:чемпионат{}, // 18 августа пройдет чемпионат Мурманской области по уличным гонкам
существительное:собрат{}, // Секундой позже рухнули и два его собрата по несчастью.
существительное:товарищ{},
существительное:панихида{}, // Панихида по Эдварду Исабекяну состоится завтра, 21 августа.
существительное:льгота{}, // В Калмыкии льготы по оплате коммунальных услуг заменят денежными выплатами
существительное:кампания{}, // Кампания по отлову нелегальных мигрантов не может увенчаться успехом
существительное:переговоры{}, // После долгих переговоров по рации они получили приказ покинуть район аварии.
существительное:подъем{}, // подъем по склону
существительное:спуск{},
существительное:навигация{}, // Продвинутая навигация по файлам
существительное:ПУТЬ{}, // путь по равнине был очень долгим (ПУТЬ)
существительное:ПОСОЛ{ ОДУШ:ОДУШ }, // У Японии теперь есть посол по делам Арктики (ПОСОЛ)
существительное:МИНИСТЕРСТВО{}, // Генпрокуратура Украины утвердила обвинительное заключение по уголовному делу о закупках реанимобилей для Министерства по чрезвычайным ситуациям (МИНИСТЕРСТВО)
существительное:ПОХОД{}, // мы начали поход по горам (ПОХОД)
существительное:УЧЕБНИК{}, // Единый учебник по истории может появиться уже через год (УЧЕБНИК)
существительное:РЕШЕНИЕ{}, // Минтранс призывал ускорить решение по допуску на работу иностранных пилотов. (РЕШЕНИЕ ПО, + ДОПУСК НА)
существительное:авиаудар{},
существительное:передвижение{}, // для получения разрешений на право передвижения по заповедной акватории
существительное:завод{}, // В Кабардино-Балкарии ликвидирован подпольный завод по переработке нефти
существительное:ПОЗИЦИЯ{}, // Официальная позиция Берлина по энергетической политике с тех пор не изменилась (ПОЗИЦИЯ ПО)
существительное:ПОЛНОМОЧИЕ{}, // полномочия по контролю за выполнением лицензионных требований (ПОЛНОМОЧИЯ ПО)
существительное:СТАВКА{}, // в связи с мировым финансовым кризисом многие банки проводят политику увеличения процентных ставок по кредитам (СТАВКА ПО)
существительное:КОМИССИЯ{}, // будет создана двусторонняя межправительственная комиссия по делимитации и демаркации де-факто существующих границ (КОМИССИЯ ПО)
существительное: удар{}, // В результате удара снежной бури "Немо" по северо-востоку США
существительное:голосование{}, // В Египте начался второй раунд голосования по Конституции страны.
существительное:ностальгия{}, // Вы иронизируете о ностальгии по тем временем
существительное:регистрация{}, // Регистрация по месту жительства. (РЕГИСТРАЦИЯ ПО)
существительное:мастер{}, // Он большой мастер по части выбивания денег из начальства. (МАСТЕР ПО)
существительное:директор{ род:муж }, // заместитель директора по маркетинговой политике (ДИРЕКТОР ПО)
существительное:директор{ род:жен },
существительное:доставка{}, // Бесплатная доставка по Москве и России
существительное:подготовка{}, // У него слабая подготовка по литературе.
существительное:книга{}, // Книга по алгоритмам и структурам данных
существительное:экзамен{}, // сдать экзамен по английскому языку
существительное:курс{}, // слушать курс по русской литературе
существительное:шаг{}, // шаги по стимулированию продаж
существительное:помощь{}, // Нужна помошь по архитектурному решению
существительное:эксперт{}, // Как отличить эксперта по безопасности от тролля?
существительное:соревнование{}, // Он занял первое место в соревнованиях по плаванию.
существительное:сравнение{}, // сравнение двигателей по разным параметрам
существительное:мера{}, // меры по борьбе
существительное:соглашение{}, // мы пришли к соглашению по вопросу уборки квартиры
существительное:комитет{}, // смешанный комитет по науке и технике
существительное:подкомитет{},
существительное:операция{}, // операция по задержанию преступников удачно завершена
существительное:хождение{}, // Хождение по газонам запрещено.
существительное:инспектор{}, // инспектор по охране труда
существительное:вызов{}, // экстренный вызов по телефону
существительное:задача{}, // Она решила задачи по математике.
существительное:справочник{},
существительное:инструкция{},
существительное:рекомендация{},
существительное:специалист{}, // специалист по выведению бородавок
существительное:работа{}, // работа по благоустройству
существительное:движение{}, // движение по спирали
существительное:месяц{}, // пятый месяц по лунному календарю
существительное:лекция{}, // Профессор читает лекции по истории немецкой философии.
существительное:прогулка{}, // он соблазнил меня на прогулку по парку
существительное:путешествие{}, // он сопровождал ее в путешествии по Африке
существительное:перемещение{}, // перемещение по линии
существительное:оценка{}, // Папа разозлился на сына из-за плохих оценок по математике
существительное:экскурсия{}, // Закончился день экскурсией по Москве.
существительное:пособие{},
существительное:обвинение{} // Ему готовят обвинение по новому делу.
}
fact сущ_предл_сущ
{
if context { Сущ_ПО_Дат предлог:по{} *:*{ падеж:дат } }
then return true
}
// Справочник по Computer Science
fact сущ_предл_сущ
{
if context { Сущ_ПО_Дат предлог:по{} @regex("[a-z]+[0-9]*") }
then return true
}
fact сущ_предл_сущ
{
if context { * предлог:по{} * }
then return false,-5 // они - братья по оружию
}
#endregion Предлог_ПО
#region Предлог_О
// ----------------- ПРЕДЛОГ 'О' ----------------------
wordentry_set Сущ_о_вин=существительное:{
лязг, // нарушил его лязг железа о железо
рокот, // далеко внизу был слышен рокот прибоя о скалы. (РОКОТ О)
удар, // позади раздался грохот удара металла о дерево. (УДАР О)
скрежет, // послышался короткий глухой скрежет железа о камень. (СКРЕЖЕТ О)
стук, // позади раздался стук копий о палубу. (СТУК О)
показание // Подсудимый заявил, что дал показания о покушении под диктовку следователей
}
fact сущ_предл_сущ
{
if context { Сущ_о_вин предлог:о{} *:*{ падеж:вин } }
then return true
}
// Подавляем по умолчанию вариант О+вин.п.
fact сущ_предл_сущ
{
if context { * предлог:о{} *:*{ падеж:вин } }
then return false,-5
}
#endregion Предлог_О
#region Предлог_К
// ----------------- ПРЕДЛОГ 'К' ----------------------
wordentry_set Сущ_к_дат={
существительное:стремление{}, // Стремление к успеху есть всегда!
существительное:подключение{}, // Питание не требует подключения к сети
существительное:бонус{}, // Матрацы идут бонусом к комплектации.
существительное:агрессия{}, // Полностью отсутствует агрессия к людям.
существительное:аксессуар{}, // Аксессуары к платью продаются отдельно
существительное:сострадание{}, // В нем есть сострадание к ближнему.
существительное:нелюбовь{}, // любовь к Б. Ельцину не помешала сделать им такой выбор.
существительное:влечение{}, // Я почувствовал к нему непреодолимое влечение.
существительное:запчасть{},
существительное:пароль{},
существительное:ключик{},
существительное:ПОХОД{}, // Там они могли спланировать поход к любым тайным вратам на этом уровне. (ПОХОД)
существительное:ВОЗВРАТ{}, // Дума поддержала возврат к смешанной системе выборов (ВОЗВРАТ)
существительное:ПРЕМИЯ{}, // Премии к праздникам обложат страховыми взносами (ПРЕМИЯ)
существительное:МИССИЯ{}, // Россия и Европа подписали соглашение по двойной миссии к Марсу (МИССИЯ)
существительное:претензия{}, // У С.Собянина много претензий к работе коммунальщиков.
существительное:ПРЕЛЮДИЯ{}, // Но это было лишь прелюдией к главному событию, потому что вскоре эта звезда превратится в сверхновую (ПРЕЛЮДИЯ)
существительное:АППЕТИТ{}, // у тебя аппетит к жизни пропал (АППЕТИТ)
существительное:неравнодушие{}, // Его подвело неравнодушие к прекрасному полу.
существительное:равнодушие{},
существительное:отвращение{}, // постепенно его охватило отвращение к себе
существительное:ПРЕНЕБРЕЖЕНИЕ{}, // Хунвэйбинские группировки отличались крайним пренебрежением к традиционной культуре (ПРЕНЕБРЕЖЕНИЕ К)
существительное:ПОДВОЗ{}, // решается вопрос с подвозом воды к объектам , имеющим социально-экономическое значение (ПОДВОЗ К)
существительное:ПОДСКАЗКА{}, // подсказка к ответу кроется как раз в новом распределении руководящих обязанностей (ПОДСКАЗКА К)
существительное:ГОТОВНОСТЬ{}, // Представитель сирийской оппозиции заявил о готовности к переговорам с властями (ГОТОВНОСТЬ К)
существительное:ПОДОЗРИТЕЛЬНОСТЬ{}, // разжигая подозрительность к Западу (ПОДОЗРИТЕЛЬНОСТЬ К)
существительное:ПРИВЛЕЧЕНИЕ{}, // решается вопрос о привлечении к дисциплинарной ответственности командира воинской части (ПРИВЛЕЧЕНИЕ К)
существительное:ПРИВЯЗКА{}, // резиденты могут с этого момента осуществлять планировку своих объектов с привязкой к местности (ПРИВЯЗКА К)
существительное:ВОПРОС{}, // возникли новые уточняющие вопросы к армянским сторонам (ВОПРОС К)
существительное:ПРЕАМБУЛА{}, // В преамбуле к проекту кодекса отмечается (ПРЕАМБУЛА К)
существительное:УСТОЙЧИВОСТЬ{}, // Поэтому для повышения устойчивости организма к простудным заболеваниям необходимо использовать препараты неспецифической профилактики (УСТОЙЧИВОСТЬ)
существительное:приложение{},
существительное:видеоприложение{},
существительное:причастность{}, // Н.Цискаридзе ответил на обвинения в причастности к нападению на С.Филина
существительное:СПОСОБНОСТЬ{}, // Это согласуется с гипотезой о том, что заразительная зевота отражает способность к эмпатии (СПОСОБНОСТЬ К)
существительное:ПРИНУЖДЕНИЕ{}, // правительство страны не принимало мер по принуждению банков к увеличению капитала, и не давало возможности иностранным инвесторам поглощать японские банки (ПРИНУЖДЕНИЕ К)
существительное:ПРОХОД{}, // открылся проход к клетке (ПРОХОД К)
существительное:ЧУВСТВИТЕЛЬНОСТЬ{}, // Обладает высокой чувствительностью к удару (ЧУВСТВИТЕЛЬНОСТЬ К)
существительное:ПРИНАДЛЕЖНОСТЬ{}, // Современное состояние климата Земли характеризуется принадлежностью к одной из межледниковых эпох голоцена (ПРИНАДЛЕЖНОСТЬ К)
существительное:НЕСПОСОБНОСТЬ{}, // В сложившейся обстановке правительство и сам царь проявили неспособность к быстрым и решительным действиям (НЕСПОСОБНОСТЬ К)
существительное:КРИТИКА{}, // Затухание бреда — появление критики к бредовым идеям (КРИТИКА К)
существительное:ПРИПРАВА{}, // Молодые листья укропа используют как вкусовую ароматическую приправу к горячим и холодным блюдам (ПРИПРАВА К)
существительное:ДВИЖЕНИЕ{}, // мы продолжали наше движение к дому. (ДВИЖЕНИЕ К)
существительное:ВОЗВРАЩЕНИЕ{}, // возвращение к власти будет происходить постепенно. (ВОЗВРАЩЕНИЕ К)
существительное:средство{}, // оставшись без средств с существованию, люди зверели (СРЕДСТВА К)
существительное:шаг{}, // мастер сделал шаг к ней. (ШАГ К)
существительное:чувство{}, // мои чувства к ней
существительное:ДОСТУП{}, // только доступ к ним закрыт. (ДОСТУП К)
существительное:УВАЖЕНИЕ{}, // а где наше уважение к смерти? (УВАЖЕНИЕ К)
существительное:поворот{}, // где поворот к мастерской? (поворот к)
существительное:ЖАЛОСТЬ{}, // Ольга вдруг ощутила жалость к этому человеку. (ЖАЛОСТЬ К)
существительное:спуск{}, // прямо перед ними начинался спуск к ручью.
существительное:дорога{}, // Бережливость - верная дорога к благосостоянию.
существительное:прием{}, // Запишите меня на завтрашний приём к доктору.
существительное:ненависть{}, // он испытывает давнюю ненависть к паукам
существительное:привязанность{}, // питать привязанность к алкоголю
существительное:склонность{}, // проявлять склонность к немотивированной агрессии
существительное:поездка{}, // крайне утомительная поездка к дедушке, живущему в деревне
существительное:применимость{}, // разработчики доказали на практике применимость данного подхода к обсчету сцен
существительное:интерес{}, // Интерес к теориям учёного не угасает и в наши дни.
существительное:доверие{}, // Я не питаю большого доверия к её талантам.
существительное:руководство{}, // План - руководство к действию.
существительное:подход{}, // Это правильный подход к решению вопроса.
существительное:повод{},
существительное:сигнал{}, // Статья послужила сигналом к дискуссии.
существительное:переход{}, // постепенный переход к рынку
существительное:безразличие{}, // безразличие к боли
существительное:призыв{}, // Он закончил речь призывом к борьбе.
существительное:сожаление{}, // Я чувствовал сожаление к нему.
существительное:подарок{}, // Я купил подарок к празднику.
существительное:приезд{}, // Сам его приезд к сыну означает примирение.
существительное:ключ{}, // ключ к шифру
существительное:описание{}, // инструмент для создания описания к лоту
существительное:отношение{}, // философское отношение к жизни
существительное:отход{}, // отход ко сну
существительное:путь{}, // На пути к смерти
существительное:тенденция{}, // тенденция к повышению цен
существительное:направление{}, // Мы пошли вместе по направлению к городу.
существительное:любовь{ одуш:неодуш }, // Она сделала это из любви к детям.
существительное:визит{}, // визит к минотавру
существительное:обращение{}, // обращение к президенту
существительное:подготовка{}, // подготовка к экзамену
существительное:путешествие{} // Путешествие к центру Земли
}
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 Сущ_через_вин={
существительное:полет{}, // полет к звездам сквозь иные измерения!
существительное:прохождение{}, // Украина пытается договориться с Турцией о прохождении танкеров с газом через Босфор
существительное:ДОРОГА{}, // по дороге через лес (ДОРОГА ЧЕРЕЗ)
существительное:трансляция{}, // руководство Ассоциации заключило договоренность с некоторыми регионами России о трансляции этого канала через местные кабельные сети
существительное:ПУТЬ{}, // это единственный путь через эти горы (ПУТЬ ЧЕРЕЗ)
существительное:ДВИЖЕНИЕ{}, // это ощущение от движения робота через болото (ДВИЖЕНИЕ ЧЕРЕЗ)
существительное:проникновение{},
существительное:транспортировка{}, // транспортировка через тоннель
существительное:смерть{}, // смерть через повешение
существительное:казнь{}, // казнь через повешение
существительное:проезд{}, // проезд через тоннель
существительное:проход{}, // проход через звездные врата
существительное:перемещение{}, // перемещение через червоточину
существительное:перелет{}, // перелет через атлантику
существительное:пролет{} // пролет через врата
}
fact сущ_предл_сущ
{
if context { Сущ_через_вин предлог:через{} *:*{ падеж:вин } }
then return true
}
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,-10
}
fact сущ_предл_сущ
{
if context { существительное:*{ одуш:одуш } предлог:сквозь{} *:*{} }
then return false,-10
}
// Подавляем по умолчанию вариант ЧЕРЕЗ+вин.п.
// Она тянула холодный лимонад через соломинку.
fact сущ_предл_сущ
{
if context { * предлог:через{} *:*{ падеж:вин } }
then return false,-5
}
fact сущ_предл_сущ
{
if context { * предлог:сквозь{} *:*{ падеж:вин } }
then return false,-5
}
#endregion Предлог_ЧЕРЕЗ_СКВОЗЬ
#region Предлог_СКВОЗЬ
// ----------------- ПРЕДЛОГ 'СКВОЗЬ' ----------------------
wordentry_set Сущ_сквозь_вин={
существительное:транспортировка{}, // транспортировка сквозь тоннель
существительное:проникновение{}, // проникновение сквозь барьер
существительное:проезд{},
существительное:проход{},
существительное:перемещение{},
существительное:перелет{},
существительное:пролет{}
}
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 Сущ_ДО_Род=существительное:{
доведение, // доведение до самоубийства
рейс, // рейс до Сан-Франциско
минута, секунда, год, зима, весна, лето, час, день, ночь, мгновение, // 10 минут до полудня
путь // Тебе предстоит долгий путь до дома
}
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 Предлог_ИЗ_ЗА
// ----------------- ПРЕДЛОГ 'ИЗ-ЗА' ----------------------
// Он выписал много книг из-за границы.
fact сущ_предл_сущ
{
if context { * предлог:из-за{} * }
then return false,-5
}
#endregion Предлог_ИЗ_ЗА
#region Предлог_ПРИ
// ----------------- ПРЕДЛОГ 'ПРИ' ----------------------
wordentry_set Сущ_ПРИ=существительное:{
изменение, // Изменение свойств при добавлении молока
хозяйство // лесное хозяйство при Правительстве Республики
}
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 Сущ_ПЕРЕД=существительное:{
долг, // это твой долг перед нашим народом!
страх, // можно считать это страхом перед людьми
остановка // существить остановку перед светофором
}
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 С_ПОМОЩЬЮ
// Эта машина приводится в движение с помощью электричества.
fact сущ_предл_сущ
{
if context { * предлог:с помощью{} * }
then return false,-10
}
#endregion С_ПОМОЩЬЮ
#region Предлог_ПОПЕРЕК
// ----------------- ПРЕДЛОГ 'незадолго до' ----------------------
// ножны лежали у Андрея поперек спины.
// ^^^^^^ ^^^^^^^
fact сущ_предл_сущ
{
if context { существительное:*{ одуш:одуш } предлог:поперек{} * }
then return false
}
#endregion Предлог_ПОПЕРЕК
/*
#region Предлог_ПРЯМО_К
// ----------------- ПРЕДЛОГ 'незадолго до' ----------------------
// он подал лимузин прямо к подъезду
// ^^^^^^^
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:прямо к{} * }
then return false,-10
}
#endregion Предлог_ПРЯМО_К
*/
#region Предлог_ПРИ_ПОМОЩИ
fact сущ_предл_сущ
{
if context { существительное:*{одуш:одуш} предлог:ПРИ ПОМОЩИ{} * }
then return false,-100
}
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:ПРИ ПОМОЩИ{} * }
then return false,-10
}
#endregion Предлог_ПРИ_ПОМОЩИ
#region Предлог_ПУТЕМ
fact сущ_предл_сущ
{
if context { существительное:*{одуш:одуш} предлог:ПУТЕМ{} * }
then return false,-100
}
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:ПУТЕМ{} * }
then return false,-10
}
#endregion Предлог_ПУТЕМ
#region Предлог_В_СООТВЕТСТВИИ_С
fact сущ_предл_сущ
{
if context { существительное:*{ одуш:одуш } предлог:В СООТВЕТСТВИИ С{} * }
then return false,-100
}
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:В СООТВЕТСТВИИ С{} * }
then return false,-10
}
#endregion Предлог_В_СООТВЕТСТВИИ_С
#region Предлог_В_ТЕЧЕНИЕ
fact сущ_предл_сущ
{
if context { существительное:*{одуш:одуш} предлог:В ТЕЧЕНИЕ{} * }
then return false,-100
}
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:В ТЕЧЕНИЕ{} * }
then return false,-10
}
#endregion Предлог_В_ТЕЧЕНИЕ
#region Предлог_ВО_ВРЕМЯ
fact сущ_предл_сущ
{
if context { существительное:*{ одуш:одуш } предлог:ВО ВРЕМЯ{} * }
then return false,-100
}
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:ВО ВРЕМЯ{} * }
then return false,-10
}
#endregion Предлог_ВО_ВРЕМЯ
#region Предлог_ВО_ИЗБЕЖАНИЕ
fact сущ_предл_сущ
{
if context { существительное:*{одуш:одуш} предлог:ВО ИЗБЕЖАНИЕ{} * }
then return false,-100
}
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:ВО ИЗБЕЖАНИЕ{} * }
then return false,-10
}
#endregion Предлог_ВО_ИЗБЕЖАНИЕ
#region Предлог_НЕСМОТРЯ_НА
fact сущ_предл_сущ
{
if context { существительное:*{одуш:одуш} предлог:НЕСМОТРЯ НА{} * }
then return false,-100
}
// штрафом наказывается проезд несмотря на запрет
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:НЕСМОТРЯ НА{} * }
then return false,-10
}
#endregion Предлог_НЕСМОТРЯ_НА
#region Предлог_МИМО
// дорога мимо полей вела.
fact сущ_предл_сущ
{
if context { существительное:*{одуш:одуш} предлог:мимо{} * }
then return false,-100
}
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:мимо{} * }
then return false,-5
}
#endregion Предлог_МИМО
#region Послелог_НАВСТРЕЧУ
// тот открыл дверь мне навстречу.
// ^^^^^ ^^^^^^^^^
fact сущ_предл_сущ
{
if context { существительное:*{} послелог:навстречу{} * }
then return false
}
#endregion Послелог_НАВСТРЕЧУ
#region Предлог_НАВСТРЕЧУ
fact сущ_предл_сущ
{
if context { существительное:*{ одуш:одуш } предлог:навстречу{} * }
then return false,-100
}
// черная машина плыла между деревьями навстречу мне.
// ~~~~~~~~~ ^^^^^^^^^
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:навстречу{} * }
then return false,-5
}
#endregion Предлог_НАВСТРЕЧУ
#region Предлог_ПРОТИВ
// Я настроил твою мать против меня.
// ~~~~ ^^^^^^
fact сущ_предл_сущ
{
if context { существительное:*{ одуш:одуш } предлог:против{} * }
then return false,-10
}
#endregion Предлог_ПРОТИВ
#region Предлог_ВМЕСТО
// старик вместо ответа махнул рукой.
// ~~~~~~ ^^^^^^
fact сущ_предл_сущ
{
if context { существительное:*{ одуш:одуш } предлог:вместо{} * }
then return false,-10
}
#endregion Предлог_ВМЕСТО
#region Предлог_РАДИ
// Животные ради удовольствия купаются
// ^^^^ ~~~~~~~~~~~~
fact сущ_предл_сущ
{
if context { существительное:*{ одуш:одуш } предлог:ради{} * }
then return false,-10
}
// делают это ради удовольствия
// ^^^ ~~~~
fact сущ_предл_сущ
{
if context { местоим_сущ:*{} предлог:ради{} * }
then return false,-10
}
#endregion Предлог_ВМЕСТО
#region Предлог_ВПЕРВЫЕ_В
// Биатлонист А.Логинов впервые в жизни завоевал медаль для сборной России
// ^^^^^^^^^
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:впервые в{} * }
then return false,-10
}
#endregion Предлог_ВПЕРВЫЕ_В
/*
#region Предлог_НЕПОДАЛЕКУ_ОТ
// Полиция расследует утечку газа неподалеку от Парижа
// ^^^^^^^^^^^^^
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:неподалеку от{} * }
then return false,-2
}
#endregion Предлог_НЕПОДАЛЕКУ_ОТ
*/
#region Предлог_БЛАГОДАРЯ
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:благодаря{} * }
then return false,-100
}
#endregion Предлог_БЛАГОДАРЯ
#region Предлог_ВПЕРЕД
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:вперед{} * }
then return false,-100
}
#endregion Предлог_ВПЕРЕД
#region Предлог_ВСЛЕД_ЗА
fact сущ_предл_сущ
{
if context { существительное:*{} предлог:вслед за{} * }
then return false,-100
}
#endregion Предлог_ВСЛЕД_ЗА
fact сущ_предл_сущ
{
if context { * * * }
then return true
}
| В нем есть сострадание к ближнему.
| существительное:сострадание{}, | 14,065,261 | [
1,
145,
245,
225,
145,
126,
145,
118,
145,
125,
225,
145,
118,
146,
228,
146,
229,
146,
239,
225,
146,
228,
145,
127,
146,
228,
146,
229,
146,
227,
145,
113,
145,
117,
145,
113,
145,
126,
145,
121,
145,
118,
225,
145,
123,
225,
145,
114,
145,
124,
145,
121,
145,
119,
145,
126,
145,
118,
145,
125,
146,
230,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
146,
228,
146,
230,
146,
236,
145,
118,
146,
228,
146,
229,
145,
115,
145,
121,
146,
229,
145,
118,
145,
124,
146,
239,
145,
126,
145,
127,
145,
118,
30,
146,
228,
145,
127,
146,
228,
146,
229,
146,
227,
145,
113,
145,
117,
145,
113,
145,
126,
145,
121,
145,
118,
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
]
|
./partial_match/56/0xA42f913368ACc30bB42144eFE839ccb17bE84718/sources/RocketToDaMoon.sol | Lock the Moon in the contract | moon.transferFrom(msg.sender, address(this), _amount);
| 11,061,697 | [
1,
2531,
326,
14987,
265,
316,
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,
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,
7344,
265,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
8949,
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
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.